如何在保留比赛之前删除行? [英] How to delete lines before a match perserving it?
问题描述
我有以下脚本来删除与单词匹配的行之前的所有行:
I have the following script to remove all lines before a line which matches with a word:
str='
1
2
3
banana
4
5
6
banana
8
9
10
'
echo "$str" | awk -v pattern=banana '
print_it {print}
$0 ~ pattern {print_it = 1}
'
它返回:
4
5
6
banana
8
9
10
但是我也想包括第一场比赛.这是所需的输出:
But I want to include the first match too. This is the desired output:
banana
4
5
6
banana
8
9
10
我该怎么做?您对另一个命令有更好的主意吗?我也尝试过 sed'0,/^ banana $/d'
,但似乎它仅适用于文件,并且我想将其与变量一起使用.
How could I do this? Do you have any better idea with another command?
I've also tried sed '0,/^banana$/d'
, but seems it only works with files, and I want to use it with a variable.
在使用awk进行比赛之前,如何获得所有行?我是说.在正则表达式中使用香蕉,这将是输出:
And how could I get all lines before a match using awk? I mean. With banana in the regex this would be the output:
1
2
3
推荐答案
只需反转 awk
中的命令:
echo "$str" | awk -v pattern=banana '
$0 ~ pattern {print_it = 1} <--- if line matches, activate the flag
print_it {print} <--- if the flag is active, print the line
'
当找到 pattern
时,将激活 print_it
标志.从那一刻起(包括该行),当标志为ON时,您将打印行.以前 print
是在检查之前完成的.
The print_it
flag is activated when pattern
is found. From that moment on (inclusive that line), you print lines when the flag is ON. Previously the print
was done before the checking.
这篇关于如何在保留比赛之前删除行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!