Reputation: 49
Looking for a simple shell script (with sed or awk) to comment out lines of a text file if a string exists in the line(s). As an example, a text file with the following:
line1 word1 word2
line2 word3 word4
line3 word5 word6
line4 word1 word7
line5 word10 word11
To be changed to:
#line1 word1 word2
line2 word3 word4
line3 word5 word6
#line4 word1 word7
line5 word10 word11
As you see, only the lines with the string "word1" are commented out.
Upvotes: 3
Views: 9526
Reputation: 2943
I believe this will do it for you.
sed -i .backup "/[[:<:]]word1[[:>:]]/s/^/#/g" file
Upvotes: 5
Reputation: 34833
Try this:
$ sed -e '/[[:<:]]word1[[:>:]]/ s/^/# /' < file
# line1 word1 word2
line2 word3 word4
line3 word5 word6
# line4 word1 word7
line5 word10 word11
How does this work? The sed
man page says,
The form of a sed command is as follows:
[address[,address]]function[arguments]
Later in the man page, it clarifies that an address can be a regular expression, which causes the function to be applied to each line matching the regular expression. So what the command given above does is, if the line contains the standalone word word1
, apply the substitution function to replace the beginning-of-line anchor with "# "
.
Upvotes: 0
Reputation: 1235
I think, your question is similar to How do I add a comment (#) in front of a line after a key word search match
Please correct me if i am wrong. I hope, this will help you.
Upvotes: 1