[英]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", eg, consider this sample file:我需要在包含模式“000”的任何行之前添加一个
#
,例如,考虑这个示例文件:
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.如果我运行该命令,它应该将
#
添加到找到“000”的任何文件的前面。 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 循环,就像这样,这似乎太复杂了:
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?如何在找到模式的任何行的前面添加
#
?
The following sed command will work for you, which does not require any capture groups:以下 sed 命令将适用于您,它不需要任何捕获组:
sed /000/s/^/#/
Explanation:解释:
/000/
matches a line with 000
/000/
匹配带有000
的行s
perform a substitution on the lines matched above s
在上面匹配的行上执行替换#
) at the beginning of the line ( ^
)^
) 插入一个井号 ( #
)这可能对你有用(GNU sed):
sed 's/.*000/#&/' file
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:问题是如何将磅符号添加到文件中的这些行,以便使 tim coopers 出色的答案更完整,我建议如下:
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 的就地编辑相关文件的能力,并制作一个备份副本,如:
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. “-i”选项将编辑和保存文件内联/就地“-i.bak”选项还将原始文件备份到 file.txt.bak 以防万一你搞砸了。
you can replace ".bak" with any suffix to your liking.您可以根据自己的喜好将“.bak”替换为任何后缀。 eg: "-i.orignal" will create the original file as: "file.txt.orignal"
例如:“-i.orignal”将创建原始文件为:“file.txt.orignal”
or use ed
:或使用
ed
:
echo -e "g/000/ s/^/#/\nw\nq" | ed -s FILENAME
or open file in ed :或在 ed 中打开文件:
ed FILENAME
and write this command并写下这个命令
g/000/ s/^/#/
w
q
Try this GNU sed command,试试这个 GNU sed 命令,
$ 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
. /000/
sed 替换仅适用于包含000
的行。 Once it finds the corresponding line, it adds #
symbol infront of it.#
符号。 And through awk,通过 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
. gsub
函数用于在包含000
的行前添加#
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.