How to delete lines before a match perserving it?

怎甘沉沦 提交于 2021-01-29 20:50:38

问题


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}
'

It returns:

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

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.

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

回答1:


Just invert the commands in the 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
'

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.




回答2:


This awk should do:

echo "$str" | awk '/banana/ {f=1} f'
banana
4
5
6
banana
8
9
10



回答3:


sed -n '/^banana$/,$p'

Should do what you want. -n instructs sed to print nothing by default, and the p command specifies that all addressed lines should be printed. This will work on a stream, and is different than the awk solution since this requires the entire line to match 'banana' exactly whereas your awk solution merely requires 'banana' to be in the string, but I'm copying your sed example. Not sure what you mean by "use it with a variable". If you mean that you want the string 'banana' to be in a variable, you can easily do sed -n "/$variable/,\$p" (note the double quotes and the escaped $) or sed -n "/^$variable\$/,\$p" or sed -n "/^$variable"'$/,$p'. You can also echo "$str" | sed -n '/banana/,$p' just like you do with awk.




回答4:


cat in.txt | awk "/banana/,0"

In case you don't want to preserve the matched line then you can use

cat in.txt | sed "0,/banana/d"


来源:https://stackoverflow.com/questions/22559017/how-to-delete-lines-before-a-match-perserving-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!