0

I've a problem : I would like to be able to delete lines beetwen two pattern in a file.

For example be able to delete the line equals to "line 1" beetwin "blablabla++" and "blablabla--"

line1
blablabla++
line1
line2
line3
blablabla--
line1

I've found a way to do it with sed :

sed '/blablabla++/,/blablabla--/{/line1/d}' ./file

It is working great. But the thing is that in my real file is more like :

line1/script
blablabla++
line1/script
line2/script
line3/script
blablabla--
line1/script

How could i do that ?

EDIT

I've choosen a bad example.

The thing is that i don't know what the line that i need to delete will be (the line will be sent as parameter). But i know one thing for sure is that they will contain "/" characters.

The thing is that when i do this :

sed '/blablabla++/,/blablabla--/{/$1/d}' ./file

The "/" that $1 contain will mess up with my sed.

Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41

3 Answers3

2

You made a bad example, because your sed cmd works both input files. I guess you want to match a pattern containing / with sed.

If you want to match something with literal /, you can escape those /s, however, it makes the codes not so easy to read, particularly you have many /s wanted to be matched, you can use \[c]pattern[c] here [c] could be any char. For example:

kent$  cat f
//one//
blablabla++
//one//
//one two//
//one three//
blablabla--
//one//

kent$  sed '/blablabla++/,/blablabla--/{\@//one//@d}' f
//one//
blablabla++
//one two//
//one three//
blablabla--
//one//

In above example, \@//one//@ is the pattern matching part.

Kent
  • 189,393
  • 32
  • 233
  • 301
1

You can escape the the / character in line1/script as below:-

$ sed '/blablabla++/,/blablabla--/{/line1\/script/d}' file
line1/script
blablabla++
line2/script
line3/script
blablabla--
line1/script

Or probably do an in-place edit with a backup stored, using the -i flag.

Another possible solution with awk

$ awk '/blablabla++/,/blablabla--/{if ($0 ~ /line1\/script/) next }1' file
line1/script
blablabla++
line2/script
line3/script
blablabla--
line1/script

The trick when using the awk solution is as soon as the pattern is met $0 ~ /line1\/script/ we are skipping the line from printing using next for the next line to be considered.

Inian
  • 80,270
  • 14
  • 142
  • 161
0

To include backslashes in a sed regular expression you can either escape them, as in /line1\/script/, or use a different character for the regex delimiter, as in #line1/script#.

l0b0
  • 55,365
  • 30
  • 138
  • 223