我有两个文件,fileA 的名称列表:
AAAAA
BBBBB
CCCCC
DDDDD
和另一个带有另一个列表的文件B:
111
222
333
444
第三个文件 C 包含一些文本:
Hello AAAAA toto BBBBB dear "AAAAA" trird BBBBBB tuizf AAAAA dfdsf CCCCC
所以我需要找到 fileC 中 fileA 的每个模式并将其替换为 fileB 模式。 有用 !但我意识到 fileC 包含像“AAAAA”这样的词,它并没有被“111”取代。
我正在这样做,但它似乎不起作用。
#! /bin/bash
while IFS= read -r lineA && IFS= read -r lineB <&3; do
sed -i -e "s/$lineA/$lineB/g" fileC
done <fileA 3<fileB
最佳答案
这对 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
关于bash - 通过文件模式查找和替换 fileS 中 fileS 的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19376259/