How to add a # before any line containing a matching pattern in BASH?

This might work for you (GNU sed):

sed 's/.*000/#&/' file

The following sed command will work for you, which does not require any capture groups:

sed /000/s/^/#/

Explanation:

  • /000/ matches a line with 000
  • s perform a substitution on the lines matched above
  • The substitution will insert a pound character (#) at the beginning of the line (^)

the question was how to add the poundsign to those lines in a file so to make tim coopers excellent answer more complete i would suggest the following:

sed /000/s/^/#/ > output.txt

or you could consider using sed's ability to in-place edit the file in question and also make a backup copy like:

sed -i.bak /000/s/^/#/ file.txt

the "-i" option will edit and save the file inline/in-place the "-i.bak" option will also backup the original file to file.txt.bak in case you screw up something.

you can replace ".bak" with any suffix to your liking. eg: "-i.orignal" will create the original file as: "file.txt.orignal"

Tags:

Bash

Grep

Sed