sed delete lines between two patterns, without the second pattern, including the first pattern

只愿长相守 提交于 2020-03-11 14:56:33

问题


my input file looks like this:

[1234]
text 
text
text

[3456]
text 
text
text

[7458]
text 
text
text

I want to delete all lines between the patterns, including FROM_HERE and excluding TO_HERE.

sed '/FROM_HERE/,/TO_HERE/{//p;d;}'

Now i have:

sed '/^\['"3456"'\]/,/^\[.*\]/{//p;d;}'

but this command does not delete the line FROM_HERE too. for 3456 at the end the input file should look like:

[1234]
text 
text
text

[7458]
text 
text
text

How can i achieve this? Thanks.


回答1:


You could delete lines from your pattern to next blank line:

sed '/^\['"3456"'\]/,/^$/{d;}' file



回答2:


Note: For the sake of the example I will only match 3456 and 7458 (and not "exactly [3456]")

You could do something like:

~$ cat t
[1234]
text1
text1
text1

[3456]
text2
text2
text2

[7458]
text3
text3
text3

~$ sed '/3456/,/7458/{/7458/!d}' t
[1234]
text1
text1
text1

[7458]
text3
text3
text3

That is: between FROM_HERE and TO_HERE (/3456/,/7458/) do the following: delete if it doesn't match TO_HERE ({/7458/!d})




回答3:


To remove the lines starting from pattern [3456] till encountering the pattern [7458](excluding the line with ending pattern) use the following command:

sed '/^\[3456\]/,/\[7458\]/{/\[7458\]/b;d;}' testfile

/\[7458\]/b - b command here is used to skip the line containing the pattern \[7458\]

d command is to delete a line The output:

[1234]
text 
text
text

[7458]
text 
text
text

https://www.gnu.org/software/sed/manual/sed.html#Branching-and-flow-control



来源:https://stackoverflow.com/questions/42898905/sed-delete-lines-between-two-patterns-without-the-second-pattern-including-the

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