首页 > 解决方案 > 如何仅提取bash中两个字符串之间多行的第一个实例?

问题描述

我的文件是:

abc
123
xyz
abc
675
xyz

我想提取:

abc
123
xyz

(123 可以是任何东西,关键是我想要第一次出现)

我尝试使用这个:

sed -n '/abc/,/xyz/p' filename

但这给了我所有的例子。我怎么能得到第一个?

标签: shellawksed

解决方案


您能否尝试使用显示的示例进行以下、编写和测试。

awk '/abc/{found=1} found; /xyz/ && found{exit}'  Input_file

或根据 Ed sir 的评论以提高效率,请尝试关注。

awk '/abc/{found=1} found{print; if (/xyz/) exit}'  Input_file

说明:为上述添加详细说明。

awk '               ##Starting awk program from here.
/abc/{              ##checking condition if a line has abc in it then do following.
  found=1           ##Setting found here.
}
found;              ##Checking condition if found is SET then print that line.
/xyz/ && found{     ##Checking if xyz found in line and found is SET then do following.
  exit              ##exit program from here.
}
'  Input_file       ##Mentioning Input_file name here.

推荐阅读