【问题标题】:Raplace a matched number with it's corresponding line in other file in sed用 sed 中其他文件中的对应行替换匹配的数字
【发布时间】:2016-03-08 19:46:52
【问题描述】:

我有一个包含此类行的文件:

|||

我想从(7219)去(6025)

我想去

到 (6025)

来自 (7219)

|||

还有一个每行一个单词的文件称为“字典”。

目标是将每个匹配项 ([0-9]+) 替换为字典文件中对应的行。

虽然我做过这样的事情:

sed -n 's/.*\(([0-9]\+)\).*/LINE IN DICTIONARY/p' input

但我不知道如何将正则表达式与文件替换连接起来。

【问题讨论】:

    标签: regex bash dictionary replace sed


    【解决方案1】:

    我会使用 GNU awk:

    $ cat -n dictionary 
         1  foo
         2  bar
         3  baz
         4  world
    $ cat file
    I want to go to (1)(2) (4)!
    $ gawk '             
        NR==FNR {words[NR]=$0; next} 
        {
            while ( match($0, /(^.*)\(([[:digit:]]+)\)(.*)/, m) ) {
                $0 = m[1] words[m[2]] m[3]
            }
            print
        }
    ' dictionary myfile
    
    I want to go to foobar world!
    

    或perl

    perl -MPath::Class -e '
        @words = file("dictionary")->slurp( chomp => 1 );
        ($text = file("myfile")->slurp) =~ s/\((\d+)\)/$words[$1 - 1]/ge;
        print $text;
    '
    

    【讨论】:

    • 有效!以及相反的过程?要将字典中存在的 inputFile 中的每个单词转换为相应的索引?谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-07-31
    • 2015-01-09
    • 2017-03-20
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多