bash

Bash Script To Comment Lines With Both Leading and Non Leading Spaces


I need to comment lines with exact patterns matching numbers with SED utility in linux(all variants) from a file containing strings. The lines in files contain both leading and non leading spaces.

If there is a number 11 in a string, it should exactly match pattern 11 and not 111,011 etc. When i use a variable, it is not substituted in the command. I also need to skip the lines which are already commented out.

a=11
b=22
sed -Ei '/[^0-9]$a[^0-9](.*[^0-9]|)$b([^0-9]|$)/s/^([[:space:]]*)/#\1/' file

Contents of file

   abc11 efg22
abc11 efg22
#abc11 efg22

Output:

   abc11 efg22
abc11 efg22
#abc11 efg22

Output without variable substitution

sed -Ei '/[^0-9]11[^0-9](.*[^0-9]|)22([^0-9]|$)/s/^([[:space:]]*)/#\1/' file

#   abc11 efg22
#abc11 efg22
##abc11 efg22

Expected output

   #abc11 efg22
#abc11 efg22
#abc11 efg22

Solution

  • This solution should address your requirements:

    sed -Ei "s/^([[:space:]]*)([^#]*\b.*$a.*\b)/\1#\2/" file