calabash
calabash

Reputation: 115

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

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.

Upvotes: 2

Views: 5144

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

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

Upvotes: 2

SLePort
SLePort

Reputation: 15481

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

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

Upvotes: 3

fredtantini
fredtantini

Reputation: 16586

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

Upvotes: 1

Related Questions