【问题标题】:How to replace some of the lines of file A according to line numbers in file B如何根据文件B中的行号替换文件A的部分行
【发布时间】:2018-03-13 22:22:55
【问题描述】:

我有两个文件 File A 和 File B。

文件 A 中的行由两个用制表符分隔的字段或单个字段组成。在文件 B 中,每行包含 3 个字段(再次用制表符分隔)第一个字段是整数,第二个和第三个字段是一些字符串。现在,如果在文件 B 中看到它的行号(在第一个字段),我想更改文件 A 中的一行。通过更改,我的意思是我想通过制表符合并文件 B 中该行的第二个和第三个字段,并将相应的行放入文件 A

例如,假设我有一个包含 3 行的文件 A

File A:
poo    foo
koo    goo
too    roo  

我有一个有 2 行的文件。

File B:
2 change-second-line with-this
3 change-third-line  with-that

最后,我想要一个包含以下内容的文件:

File final:
poo    foo
change-second-line    with-this
change-third-line    with-that  

有没有办法做到这一点?一般来说,在提问的同时,我也会放一个代码 sn-p 来显示我的努力,但这次我什至无法开始编写来做到这一点。

【问题讨论】:

    标签: linux file awk sed text-processing


    【解决方案1】:
    awk 'FNR==NR{arr[$1]=substr($0,index($0,$2));next}
         FNR in arr{print arr[FNR];next}1
        ' fileB fileA
    

    awk 'FNR==NR{arr[$1]=substr($0,length($1)+2);next}
         FNR in arr{print arr[FNR];next}1
        ' fileB fileA
    

    测试结果:

    $ cat fileA
    poo    foo
    koo    goo
    too    roo  
    
    $ cat fileB
    2 change-second-line with-this
    3 change-third-line  with-that
    
    $ awk 'FNR==NR{arr[$1]=substr($0,index($0,$2));next}FNR in arr{print arr[FNR];next}1' fileB fileA
    poo    foo
    change-second-line with-this
    change-third-line  with-that
    
    # OR will be faster too
    $ awk 'FNR==NR{arr[$1]=substr($0,length($1)+2);next}FNR in arr{print arr[FNR];next}1' fileB fileA
    poo    foo
    change-second-line with-this
    change-third-line  with-that
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 2015-12-20
      • 2019-01-16
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      相关资源
      最近更新 更多