Matching pattern span multiple line and remove those matching lines

心已入冬 提交于 2019-12-11 20:12:58

问题


I was trying to use sed to do the following:

In file looks something like:

 FirstLine
 SecondLineEEE
 AAAblablabla
 ForthLineEEE
 FifthLine
 LastLine

I want to remove EEE (but keep the rest of second line) and the whole line starting with AAA and keep other part of the file intact.

The expected result is (as seen, if the following line doesn't start with AAA, it will be kept, that's why I need to match multiple lines.)

 FirstLine
 SecondLine
 ForthLineEEE
 FifthLine
 LastLine

How should I do it? Thanks in advance!


回答1:


This might work for you:

echo -e "FirstLine\nSecondLineEEE\nAAAblablabla\nLastLine" |
sed '/EEE$/{N;s/EEE\nAAA.*//}'
FirstLine
SecondLine
LastLine



回答2:


fge@erwin ~ $ sed '/EEE$/d; /^AAA/d' <<EOF
> FirstLine
> SecondLineEEE
> AAAblablabla
> LastLine
> EOF
FirstLine
LastLine

/re/d will remove all lines from the input matching regex re. Adapt the patterns to your needs.




回答3:


May be this could work -

sed '/EEE$/N;s/\(.*\)EEE\nAAA.*/\1/' filename

Test:

[jaypal:~/Temp] cat file
FirstLine
SecondLineEEE
AAAblablabla
ForthLineEEE
FifthLine
LastLine

[jaypal:~/Temp] sed '/EEE$/N;s/\(.*\)EEE\nAAA.*/\1/' file
FirstLine
SecondLine
ForthLineEEE
FifthLine
LastLine


来源:https://stackoverflow.com/questions/8635054/matching-pattern-span-multiple-line-and-remove-those-matching-lines

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