cat file1
xi=zaoshui jiao=@E0488_5@
chi=fan da qiu=@E0488_3@
gong=zuo you xi @E0977_5@
cat file2
@E0488_3@ @E21562_3@
@E0488_5@ @E21562_5@
@E0977_3@ @E21630_3@
@E0977_5@ @E21630_5@
@E0977_6@ @E21631_1@
目的:如果在file2 $ 1中找到file1中的$ NF,则将file1中的$ NF替换为file2 $ 2.otherwise,不做任何更改。
我的代码:
awk 'NR==FNR{a[$1]=$2;next}
{split($NF,a,"=");for($NF in a){$NF=a[$NF]}}1' test2.txt test1.txt
但它出现了错误:
awk: cmd. line:1: NR==FNR{a[$1]=$2;next}{split($NF,a,"=");for($NF in a){$NF=a[$NF]}}1
awk: cmd. line:1: ^ syntax error
我的代码看起来是否合适?似乎语法问题发生了。我该如何改进呢?
我的期望输出:
xi=zaoshui jiao=@E21562_5@
chi=fan da qiu=@E21562_3@
gong=zuo you xi @E21630_5@
答案 0 :(得分:2)
不完全确定,但是请您试着跟随并告诉我这是否对您有帮助。
awk 'FNR==NR{a[$1]=$NF;next} ($NF in a){$NF=a[$NF]} 1' FS="=" file2 FS='[= ]' OFS="=" file1
输出如下。
xi=zaoshui jiao=@E0488_5@
chi=fan da qiu=@E0488_3@
gong=zuo you xi @E0977_5@
编辑: 现在也为此添加说明。
awk '
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when first Input_file named file2 is being read.
a[$1]=$NF; ##making an array named a whose index is $1 of current line and value is last field of the current line.
next ##next will skip all the further statements now.
}
($NF in a){ ##Checking condition here if last field of current line of Input_file file1 is present in array a if yes then do following.
$NF=a[$NF] ##creating last field value to array a value whose index is $NF of current line in Input_file file1.
}
1 ##1 will print the lines for Input_file file1.
' FS="=" file2 FS='[= ]' OFS="=" file1 ##Setting FS="=" for file2 and setting FS value to either = or space for file1 and setting OFS value to = for file1 too.
答案 1 :(得分:2)
for($NF in a)
语法无效,($NF
给出值)它可以像
for (var in array)
body
阅读更多内容:GNU AWK Scanning-an-Array
sub($NF,a[$NF])
保留原始字段分隔符,因为最后一个记录,最后一个字段之前有空格,而其他行最后一个字段之前有=
,假设值不重复而不是最后一个字段。测试结果:
$ cat file1
xi=zaoshui jiao=@E0488_5@
chi=fan da qiu=@E0488_3@
gong=zuo you xi @E0977_5@
$ cat file2
@E0488_3@ @E21562_3@
@E0488_5@ @E21562_5@
@E0977_3@ @E21630_3@
@E0977_5@ @E21630_5@
@E0977_6@ @E21631_1@
$ awk 'FNR==NR{a[$1]=$NF;next}($NF in a){sub($NF,a[$NF])}1' file2 FS='[ =]' file1
xi=zaoshui jiao=@E21562_5@
chi=fan da qiu=@E21562_3@
gong=zuo you xi @E21630_5@
答案 2 :(得分:2)
我的代码如下所示,希望它可能会有所帮助,即使它不是最有效的答案。
awk '$NF ~ /=/ {gsub("="," @ ",$NF)}{print $0}' file1 > file3
cat file3
xi=zaoshui jiao @ @E0488_5@
chi=fan da qiu @ @E0488_3@
gong=zuo you xi @E0977_5@
如你所说,将file1替换为file3,如果在file2 $ 1中找到file3的$ NF,则用file2 $ 2替换file3的$ NF
awk 'NR==FNR {a[$1]=$2;next}($NF in a){$NF=a[$NF]}1' file2 file3 | sed 's/ @ /=/g'
xi=zaoshui jiao=@E21562_5@
chi=fan da qiu=@E21562_3@
gong=zuo you xi @E21630_5@