一种使用方式GNU awk
:
awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub(i, array[i]) }1' master.txt file.txt
结果:
The Id of the customer is 5. He is from Grg.
The Name of the machine is ASB
The id is 4. He is from Psg.
要将输出保存到文件:
awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub(i, array[i]) }1' master.txt file.txt > name_of_your_output_file.txt
解释:
FNR==NR { ... } # FNR is the current record number, NR is the record number
# so FNR==NR simply means: "while we process the first file listed
# in this case it's "master.txt"
array[$1]=$2 # add column 1 to an array with a value of column 2
next # go onto the next record
{ # this could be written as: FNR!=NR
# so this means "while we process the second file listed..."
for (i in array) # means "for every element/key in the array..."
gsub(i, array[i]) # perform a global substitution on each line replacing the key
# with it's value if found
}1 # this is shorthand for 'print'
添加单词边界使匹配更加严格:
awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub("\\<"i"\\>", array[i]) }1' master.txt file.txt