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

爱⌒轻易说出口 提交于 2020-12-28 09:56:26

问题


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?


回答1:


This might work for you (GNU sed):

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



回答2:


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



回答3:


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"




回答4:


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



回答5:


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.


来源:https://stackoverflow.com/questions/24230117/how-to-add-a-before-any-line-containing-a-matching-pattern-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!