Santhoshkumar Ramachandran Santhoshkumar Ramachandran - 3 months ago 8
Bash Question

How to find next [ ] using shell script and comment all the lines between them?

I'm trying to comment a set of lines using Shellscript.

$>cat abc.txt
[entry1]
abcd
efgh
ijkl
mnop

[entry2]
abcd
efgh
ijkl
mnop
qust

[entry3]
abcd
efgh
ijkl
mnop
qrst
uvwx
yz

[entry4]
...
...
...
...


from the above file, i want to find the [entry2] and comment all the lines between [entry2] to [entry3]
Note: The number of lines between entries are not same.

I want output like below..

$>cat abc.txt
[entry1]
abcd
efgh
ijkl
mnop

#[entry2]
#abcd
#efgh
#ijkl
#mnop
#qust

[entry3]
abcd
efgh
ijkl
mnop
qrst
uvwx
yz

[entry4]
...
...
...
...


I'm thinking that we can do this with sed. but not sure about exact usage.

Can anyone suggest?

Answer

As you guessed, sed is your friend. You could match text in between pattern to achieve what you want.

sed -E '/^\[entry2\]/,/^$/s/^(.)/#\1/' file

[entry1]
abcd
efgh
ijkl
mnop

#[entry2]
#abcd
#efgh
#ijkl
#mnop
#qust

[entry3]
abcd
efgh
ijkl
mnop
qrst
uvwx
yz

[entry4]
...
...
...
...

How it works

  • /pattern1/,/pattern2/ matches text in between the patterns including the patterns
  • The command that follows, s here is applied on all such lines.
  • Now since you don't need need to comment blank lines we need to check the line for at least one non-blank character( Note the . which accomplishes this).
  • The ^ matches the beginning of the line
  • The () is used for grouping characters and \1 is used in the replacement part to replace the groups
  • Now read the lines together

Note

The [] has special meaning in sed, they represent character ranges. To search for a literal[ or ] you need to escape them - ie \[ - as we've done here.


Comments