【问题标题】:Adding Comments to File向文件添加注释
【发布时间】:2016-04-25 12:33:04
【问题描述】:

我们有两个文件file1.txt和file2.txt

file1.txt

PropertyA
PropertyB
PropertyC
####Some Comments##
PropertyA
PropertyB
PropertyC
PropertyD

file2.txt

#This is Property A
PropertyA=valueforpropertyA

PropertyB=valueforpropertyB
#Adding values to Property C
PropertyC=valueforpropertyC
#Value for Property D
PropertyD=valueforpropertyD
#This is Property E
PropertyE=valueforpropertyE

PropertyF=valueforpropertyF
#End of Properties
#End of values
#End of Files

在file1.txt 的####Some Comments## 部分中出现的属性之后,我们使用以下命令将值从file2.txt 写入file1.txt。

awk -F'=' 'FNR==NR{if (p) a[$0]; else {print; if ($0 ~ /####Some Comments##/) p=1} next}
  $1 in a' file1.txt file2.txt > _file1.txt && mv _file1.txt file1.txt

这是输出:

PropertyA
PropertyB
PropertyC
####Some Comments##
PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
PropertyC=valueforpropertyC
PropertyD=valueforpropertyD

我们需要上面的命令来打印出出现在 file2.txt 中的 cmets。这应该是 file1.txt 的输出

*PropertyA
PropertyB
PropertyC
####Some Comments##
#This is Property A
PropertyA=valueforpropertyA
PropertyB=valueforpropertyB
#Adding values to Property C
PropertyC=valueforpropertyC
#Value for Property D
PropertyD=valueforpropertyD
#End of Properties
#End of values
#End of Files*

如何使用上面的命令来做到这一点?

【问题讨论】:

  • 一些混淆的 awk 代码。

标签: bash shell unix


【解决方案1】:
awk -F'=' 'FNR==NR{if (p) a[$0]; else {print; if ($0 ~ /####Some Comments##/) p=1} next} { if($1 in a) { print a[$1] } else if ($1 ~ /^#/){ print }}' file1.txt file2.txt > _file1.txt && mv _file1.txt file1.txt

试试这个....

我刚刚添加了一个额外的括号,用于打印 a-array 是否包含 $1 的行(如果不包含,则为注释)

【讨论】:

  • 嗨 Joda,感谢您的回复,我已经尝试了您的命令。但是,收到错误消息意外换行符或字符串结尾 //{ print }// awk: cmd.行:1:FNR==NR{if (p) a[$0];否则 {打印; if ($0 ~ /####Some Comments##/) p=1} next} { if($1 in a) { print a[$1] } else if ($1 ~ /^#/){ print } awk:命令。 line:1: ^ 意外的换行符或字符串结尾
  • Thiis 是我的命令:awk -F'=' 'FNR==NR{if (p) a[$0];否则 {打印; if ($0 ~ /####Some Comments##/) p=1} next} { if($1 in a) { print a[$1] } else if ($1 ~ /^#/){ print }' file1 .txt 文件 2.txt > _file1.txt && mv _file1.txt 文件 1.txt。我该如何解决这个问题?
  • Ups,我最后错过了一个“}” :) 我编辑了我的答案
猜你喜欢
  • 2013-04-11
  • 2022-06-23
  • 1970-01-01
  • 2015-05-03
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多