添加注释到文件

时间:2016-04-25 12:33:05

标签: bash shell unix

我们有两个文件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中出现的注释。这应该是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*

如何使用上述命令完成此操作?

1 个答案:

答案 0 :(得分:0)

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美元或不包含1美元的行(如果没有,则是评论)