使用sed多次替换文件中找到的文本

时间:2017-04-18 15:40:01

标签: awk sed

如何使用sed替换filetobeprocessed.txt中的文本,

,其名称和电话号码可能在其中:

table_open_cache

以每行为单位包含文本。要查找的文本存在于fileA.txt中,替换字符串位于fileB.txt中。

例如,fileA.txt

可能有

Name3 john.D,

和fileB.txt 可能有

人:John Diamen,

所以filetobeprocessed.txt应该成为:

Name3 john.D
Name6 mary.D
Name7 kelly.O
etc

当然,由于要处理的文件,fileA和fileB都很大,我们可能在搜索字符串和替换字符串中找到任何字符,所以我的示例是基本的,并不涵盖所有字符存在于filetobeprocessed.txt中 所以我需要一种方法,使用sed来进行搜索和替换,但是对于fileA.txt中找到的每一行及其等效字符串,在fileB.txt中找到相同的数字行

sed -f -

结合

Person: John Diamen
Name6 mary.D
Name7 kelly.O

要替换的sed的/ \ string \ b /替换字符串/ g'file.xml

我找不到的,是一种方法,用于fileA.txt的每一行,其中包含要搜索的所有字符串,以及每个相应的替换行,可在fileB.txt中找到

2 个答案:

答案 0 :(得分:0)

在awk中:

$ awk '
NR==FNR {               # hash the first file to a
    a[$0]=$0; next }
{
    if(FNR in b) {      # process the third file to b
        b[b[FNR]]=$0
        delete b[FNR] }
    else b[FNR]=$0      # process the second file to b
}
END {                   # after all files are processed and in memory
    for(i in a)         # go thru all entries of first file
        if(i in b)      # if entry found in second file
            print b[i]  # replace with the value of third file
        else 
            print a[i]  # otherwise print the entry from the first file
}' filetobeprocessed.txt fileA.txt fileB.txt  # mind the order
Name6 mary.D
Person: John Diamen
Name7 kelly.O

答案 1 :(得分:0)

要求不明确,但这样的事情可能有效。

示例文件

==> file <==
Name1 2377
Name2 2910
Name3 8458
Name4 1522
Name5 5855
Name6 1934
Name7 8106
Name8 1735
Name9 4849
Name10 1518

==> fileA <==
Name3
Name7

==> fileB <==
Person: John Smith
Person: Mr Brown



$ awk -F'\t' 'NR==FNR {a[$1]=$2; next} 
              $1 in a {$1=a[$1]}1' <(paste fileA fileB) FS='[[:space:]]' file

Name1 2377
Name2 2910
Person: John Smith 8458
Name4 1522
Name5 5855
Name6 1934
Person: Mr Brown 8106
Name8 1735
Name9 4849
Name10 1518

这假定查找文件fileAfileB不是太大,因为对要替换的file

没有限制

假设替换文本中没有特殊字符

,可以使用sed完成相同的操作
$ sed -f <(paste fileA fileB | sed -r 's_(.*)\t(.*)_s/\1/\2/_') file
相关问题