sed - comment a matching line and x lines after it
10,737
Solution 1
You can do this by applying a regular expression to a set of lines:
sed -e '/myprocess/,+4 s/^/#/'
This matches lines with 'myprocess' and the 4 lines after them. For those 4 lines it then inserts a '#' at the beginning of the line.
(I think this might be a GNU extension - it's not in any of the "sed one liner" cheatsheets I know)
Solution 2
sed '/\[myprocess/ { N;N;N;N; s/^/#/gm }' input_file
Solution 3
Using string concatenation and default action in awk
.
http://www.gnu.org/software/gawk/manual/html_node/Concatenation.html
awk '/myprocess/{f=1} f>5{f=0} f{f++; $0="#" $0} 1' foo.txt
or if the block always ends with empty line
awk '/myprocess/{f=1} !NF{f=0} f{$0="#" $0} 1' foo.txt
Related videos on Youtube
Comments
-
Sanjan Grero over 1 year
I need help with using sed to comment a matching lines and 4 lines which follows it. in a text file.
my text file is like this:
[myprocess-a] property1=1 property2=2 property3=3 property4=4 [anotherprocess-b] property1=gffgg property3=gjdl property2=red property4=djfjf [myprocess-b] property1=1 property4=4 property2=2 property3=3
I want to prefix # to all the lines having text '[myprocess' and 4 lines that follows it expected output:
#[myprocess-a] #property1=1 #property2=2 #property3=3 #property4=4 [anotherprocess-b] property1=gffgg property3=gjdl property2=red property4=djfjf #[myprocess-b] #property1=1 #property4=4 #property2=2 #property3=3
Greatly appreciate your help on this.
-
Mausy5043 almost 7 years
sed: -e expression #1, char 12: unexpected ','
:-( -
Flexo almost 7 yearsWhat version of see? Odds are it's either old or not got the gnu extensions.
-
Mausy5043 almost 7 yearssed 4.2.2. It's the Debian default so, yeah, probably missing GNU extensions
-
wisbucky almost 5 yearsgnu documentation for this: gnu.org/software/sed/manual/html_node/Range-Addresses.html
-
Vikas Goel about 2 yearsHow does one do it for all the lines after a matching pattern?
-
Flexo about 2 yearsOff the top of my head I think changing +4 to $ would do that.