这是一份很好的工作GNU awk
:
$ cat replace.awk
FILENAME=="filea" {
a[FNR]=$0
next
}
FILENAME=="fileb" {
b[a[FNR]]=$0
next
}
{
for (i=1;i<=NF;i++) {
printf "%s%s",(b[$i]?b[$i]:$i),(i==NF?RS:FS)
}
}
演示:
$ awk -f replace.awk filea fileb filec
Hello 111 toto 222 dear 111 trird BBBBBB tuizf 111 dfdsf 333
sehe的解决方案:
FILENAME==ARGV[1] { # Read the first file passed in
find[FNR]=$0 # Create a hash of words to replace
next # Get the next line in the current file
}
FILENAME==ARGV[2] { # Read the second file passed in
replace[find[FNR]]=$0 # Hash find words by the words to replace them
next # Get the next line in the current file
}
{ # Read any other file passed in (i.e third)
for (i=1;i<=NF;i++) { # Loop over all field & do replacement if needed
printf "%s%s",(replace[$i]?replace[$i]:$i),(i==NF?RS:FS)
}
}
对于替换忽略单词边界:
$ cat replace.awk
FILENAME==ARGV[1] {
find[FNR]=$0
next
}
FILENAME==ARGV[2] {
replace[find[FNR]]=$0
next
}
{
for (word in find)
gsub(find[word],replace[find[word]])
print
}
演示:
$ awk -f replace.awk filea fileb filec
Hello 111 toto 222 dear "111" trird 222B tuizf 111 dfdsf 333