简体   繁体   English

如何使用bash附加到文件中包含匹配模式的行的开头和结尾?

[英]How to append to beginning and end of line containing a matching pattern in a file using bash?

I need to add a <!-- to the beginning of a line and --> to the end of a line for each line in a xml file if a certain string is present. 如果存在某个字符串,我需要为xml文件中的每一行添加<!--到行的开头,并且-->到行的结尾。 so, for example, if BlueCard is the string I want to match and the file looks like this currently: 因此,例如,如果BlueCard是我要匹配的字符串,并且文件当前看起来像这样:

RedCard
BlueCard
GreenCard

I want the new file to look like: 我希望新文件看起来像:

RedCard
<!--BlueCard-->
GreenCard

How can this be done? 如何才能做到这一点?

与sed:

sed 's/.*BlueCard.*/<!--&-->/' file

You can also match pattern and then apply substitute( s ) for all lines that matches. 您也可以搭配的图案,然后应用替代( s为匹配所有行)。

sed '/BlueCard/ s/.*/<!--&-->/' test
  • & Here it selects everything that is matched by .* &这将选择通过匹配的一切.*

try in awk too once. 也尝试一次awk。

awk '/BlueCard/{print "<!--" $0 "-->";next} 1'  Input_file

So looking for string BlueCard in a line if it finds it then print the comments with that line, using next will not skip all further statements. 因此,如果在一行中找到字符串BlueCard,则在该行中查找该字符串,然后在该行中打印注释,使用next不会跳过所有其他语句。 using 1 will print everything apart from line having BlueCard as it is already taken care by the condition itself. 使用1将打印除具有BlueCard的行以外的所有内容,因为条件本身已对其进行了注意。

Solution 2nd: Using sub utility of awk here. 解决方案2:在此处使用awk的子实用程序。

awk '{sub(/BlueCard/,"<!--&-->")} 1'   Input_file

Simply substituting string BlueCard here with the comments and printing everything then. 只需在此处用注释替换字符串BlueCard,然后打印所有内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM