请参阅以下脚本 - 关于此
nawk 'NR==FNR { a[$1]=$2 ; next} {for ( i in a) gsub(i,a[i])}1' file.dat 1.txt
1.txt
ioiufeioru
dfoiduf
MO_CIF_INP438
fjkdj MO_CIF_INP
dsjhdf BP_LINKED_TETES
dehdueuh MO_INP_BPRESP
文件
MO_CIF_INP TRO_MO_CIF_INP
BP_LINKED_TETES TRO_BP_LINKED_TETES
MO_BPID TRO_MO_BPID
MO_INP_BPRESP TRO_MO_INP_BPRESP
上述脚本的输出是
ioiufeioru
dfoiduf
TRO_MO_CIF_INP438
fjkdj TRO_MO_CIF_INP
dsjhdf TRO_BP_LINKED_TETES
dehdueuh TRO_MO_INP_BPRESP
我的目的是只替换匹配的单词,而不是
MO_CIF_INP438
替换上述情况下的所有单词。我们如何使用单词搜索?我尝试了以下情况,但没有成功
1.
nawk 'NR==FNR { a[$1]=$2 ; next} {for ( i in a) gsub(/i/,a[i])}1' file.dat 1.txt
TRO_BP_LINKED_TETESoTRO_BP_LINKED_TETESufeTRO_BP_LINKED_TETESoru
dfoTRO_BP_LINKED_TETESduf
MO_CIF_INP438
fjkdj MO_CIF_INP
dsjhdf BP_LINKED_TETES
dehdueuh MO_INP_BPRESP
2.
nawk 'NR==FNR { a[$1]=$2 ; next} {for ( i in a) gsub(\<i\>,a[i])}1' file.dat 1.txt
nawk: syntax error at source line 1
context is
NR==FNR { a[$1]=$2 ; next} {for ( i in a) >>> gsub(\ <<< <i\>,a[i])}1
nawk: illegal statement at source line 1
答案1
您可以尝试以下方法:
awk '
# Read entire file.dat in an array indexed at column1 having value of column2
NR==FNR {
a[$1]=$2;
# Skip the next action statements until file.dat is completely stored
next
}
# For each index element of array
{
for(i in a) {
# Iterate over each values of line from 1.txt file
for(x=1;x<=NF;x++) {
# If an exact match is found replace it with array element else leave it as is.
$x=(i==$x)?a[i]:$x
}
}
}1' file.dat 1.txt
$ head file.dat 1.txt
==> file.dat <==
MO_CIF_INP TRO_MO_CIF_INP
BP_LINKED_TETES TRO_BP_LINKED_TETES
MO_BPID TRO_MO_BPID
MO_INP_BPRESP TRO_MO_INP_BPRESP
==> 1.txt <==
ioiufeioru
dfoiduf
MO_CIF_INP438
fjkdj MO_CIF_INP
dsjhdf BP_LINKED_TETES
dehdueuh MO_INP_BPRESP
$ awk '
NR==FNR {
a[$1]=$2;
next
}
{for(i in a) {
for(x=1;x<=NF;x++) {
$x=(i==$x)?a[i]:$x
}
}
}1' file.dat 1.txt
ioiufeioru
dfoiduf
MO_CIF_INP438
fjkdj TRO_MO_CIF_INP
dsjhdf TRO_BP_LINKED_TETES
dehdueuh TRO_MO_INP_BPRESP