Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

sed

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?

like image 418
Village Avatar asked Jun 15 '14 13:06

Village


People also ask

Can I have 2 Gmail accounts?

Can I Have Multiple Gmail Accounts? The short answer is, "Yes, you can have multiple Gmail accounts." Many professionals have both a personal Gmail account and a work Gmail account tethered to their CRM.


2 Answers

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 (^)
like image 157
Tim Cooper Avatar answered Oct 14 '22 17:10

Tim Cooper


This might work for you (GNU sed):

sed 's/.*000/#&/' file
like image 30
potong Avatar answered Oct 14 '22 15:10

potong