简体   繁体   English

用awk附加到文件的某些行,不匹配的行保持不变

[英]Append to certain line of file with awk, leaving non-matching lines unchanged

given file test and its content: 给定的文件测试及其内容:

bcd://dfl
sf

I would like to append extra information to the line having certain content (starting with bcd ) While the following script works 我想将额外的信息添加到具有某些内容的行中(以bcd开头),而以下脚本有效

awk '/bcd*/ {print $0", extra information"} ' test > test.old && mv test.old test

it removes the non matching lines. 删除不匹配的行。 ( sf ) 平方英尺

Is it possible to preserve them in the output file? 是否可以将它们保存在输出文件中?

As discussed over in the comments appending a {..}1 at the end will solve your problem, 如注释中所讨论的那样 ,在末尾附加{..}1将解决您的问题,

awk '/^bcd/ {print $0", extra information"; next} 1' file

because the /<pattern>/{<action>} is applied to the lines only matching the <pattern> , the other lines are just printed as-is, {..}1 is a always-true-no-matter-what condition to print lines. 因为/<pattern>/{<action>}应用于<pattern>匹配的行,所以其他行仅按原样打印, {..}1始终为真的任何内容打印行的条件。

awk '/^bcd/ {$0 = $0 ", extra information"} 1' test

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

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