Village
Village

Reputation: 24423

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

I need to add a # before any line containing the pattern "000", e.g., consider this sample file:

This is a 000 line.
This is 000 yet ano000ther line.
This is still yet another line.

If I run the command, it should add # to the front of any files where "000" was found. The result would be this:

#This is a 000 line.
#This is 000 yet ano000ther line.
This is still yet another line.

The best I can do is a while loop, like this, which seems too complicated:

while read -r line
do
    if [[ $line == *000* ]]
    then
          echo "#"$line >> output.txt
    else
          echo $line >> output.txt
    fi
done < file.txt

How can I add a # to the front of any line where a pattern is found?

Upvotes: 37

Views: 55766

Answers (5)

geegee
geegee

Reputation: 143

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"

Upvotes: 4

potong
potong

Reputation: 58473

This might work for you (GNU sed):

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

Upvotes: 30

Baba
Baba

Reputation: 850

or use ed:

echo -e "g/000/ s/^/#/\nw\nq" | ed -s FILENAME

or open file in ed :

ed FILENAME

and write this command

g/000/ s/^/#/
w
q

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174766

Try this GNU sed command,

$ sed -r '/000/ s/^(.*)$/#\1/g' file
#This is a 000 line.
#This is 000 yet ano000ther line.
This is still yet another line.

Explanation:

  • /000/ sed substitution only works on the line which contans 000. Once it finds the corresponding line, it adds # symbol infront of it.

And through awk,

$ awk '/000/{gsub (/^/,"#")}1' file
#This is a 000 line.
#This is 000 yet ano000ther line.
This is still yet another line
  • gsub function is used to add # infront of the lines which contains 000.

Upvotes: 0

user142162
user142162

Reputation:

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 (^)

Upvotes: 73

Related Questions