2

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.

calabash
  • 115
  • 1
  • 7
  • delete all lines from `[3456]`(including) to `[7458]` ? – RomanPerekhrest Mar 20 '17 at 08:36
  • no it does not. i have updated my question – calabash Mar 20 '17 at 08:46
  • Possible duplicate of [sed or awk deleting lines between pattern matches, excluding the second token's line](http://stackoverflow.com/questions/13177772/sed-or-awk-deleting-lines-between-pattern-matches-excluding-the-second-tokens) [How to delete lines between the pattern but keep the line with the second pattern](http://stackoverflow.com/questions/20655694/how-to-delete-lines-between-the-pattern-but-keep-the-line-with-the-second-patter) – fredtantini Mar 20 '17 at 08:57
  • Possible duplicate of [How, using sed, can one extract a regex-delimited range except for the last line?](http://stackoverflow.com/questions/39036889/how-using-sed-can-one-extract-a-regex-delimited-range-except-for-the-last-line) – stevesliva Mar 21 '17 at 01:55

3 Answers3

3

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

sed '/^\['"3456"'\]/,/^$/{d;}' file
SLePort
  • 15,211
  • 3
  • 34
  • 44
2

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

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

fredtantini
  • 15,966
  • 8
  • 49
  • 55