5

我有两个文件, fileA 有一个名称列表:

AAAAA 
BBBBB
CCCCC
DDDDD

和另一个带有另一个列表的 fileB :

111 
222
333
444

和带有一些文本的第三个 fileC :

Hello AAAAA toto BBBBB dear "AAAAA" trird BBBBBB tuizf AAAAA dfdsf CCCCC

所以我需要用fileB模式查找并替换fileC中fileA的每个模式。有用 !但我意识到 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
4

3 回答 3

3

这是一份很好的工作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
于 2013-10-15T08:38:42.300 回答
2
sed 's/.*/s/' fileA | paste -d/ - fileA fileB | sed 's/$/\//' | sed -f - fileC

正确和更快的版本是

paste -d/ fileA fileB | sed 's/^/s\//;s/$/\/g/' | sed -f - fileC
于 2013-10-15T08:35:40.667 回答
1

两相火箭:

sed -e "$(paste file[AB] | sed 's/\(.*\)\t\(.*\)/s\/\1\/\2\/g;/')" fileC 

这样做是使用以下命令创建一个临时 sed 脚本paste file[AB] | sed 's/\(.*\)\t\(.*\)/s\/\1\/\2\/g;/'

s/AAAAA/111/g;
s/BBBBB/222/g;
s/CCCCC/333/g;
s/DDDDD/444/g;

然后将其fileC作为输入运行

于 2013-10-15T08:37:03.363 回答