简体   繁体   English

如何打印匹配第一次出现的单词之间的所有行?

[英]How to Print All line between matching first occurrence of word?

input.txt输入文件

ABC
CDE
EFG
XYZ
ABC
PQR
EFG

From above file i want to print lines between 'ABC' and first occurrence of 'EFG'.从上面的文件中,我想打印 'ABC' 和第一次出现的 'EFG' 之间的行。

Expected output :预期输出:

ABC
CDE
EFG
ABC
PQR
EFG 

How can i print lines from one word to first occurrence of second word?如何打印从一个单词到第二个单词第一次出现的行?

EDIT: In case you want to print all occurrences of lines coming between ABC to DEF and leave others then try following.编辑:如果您想打印所有出现在 ABC 到 DEF 之间的行并留下其他行,请尝试以下操作。

awk '/ABC/{found=1} found;/EFG/{found=""}' Input_file


Could you please try following.你能不能试试以下。

awk '/ABC/{flag=1} flag && !count;/EFG/{count++}' Input_file
$ awk '/ABC/,/EFG/' file

Output:输出:

ABC
CDE
EFG
ABC
PQR
EFG

This might work for you (GNU sed):这可能对你有用(GNU sed):

sed -n '/ABC/{:a;N;/EFG/!ba;p}' file

Turn off implicit printing by using the -n option.使用-n选项关闭隐式打印。

Gather up lines between ABC and EFG and then print them.收集ABCEFG之间的线条,然后打印它们。 Repeat.重复。

If you want to only print between the first occurrence of ABC to EFG , use:如果您只想在第一次出现ABCEFG之间打印,请使用:

sed -n '/ABC/{:a;N;/EFG/!ba;p;q}' file

To print the second through fourth occurrences, use:要打印第二次到第四次出现,请使用:

sed -En '/ABC/{:a;N;/EFG/!ba;x;s/^/x/;/^x{2,4}$/{x;p;x};x;}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM