【问题标题】:Bash - Replace one string in one with another string from another fileBash - 用另一个文件中的另一个字符串替换一个字符串
【发布时间】:2013-08-22 17:14:44
【问题描述】:

我有两个已排序的文本文件。文件 A 的数据如下所示:

adam
humanities

antwon
sciences

bernard
economics

castiel
sciences

dmitri
informatics

zoe
mathematics

文件 B 的数据如下所示:

adamburnston
antwonreed
justbernard
castiel
dmitrivalchenkov
zoematthews

我需要将文件 A(adam) 中的行替换为文件 B(adamburnston) 中的行。这两个文件都按字母顺序排列,并且包含相同数量的条目。我怎样才能达到这个结果?

预期输出:

adamburnston
humanities

antwonreed
sciences

justbernard
economics

castiel
sciences

dmitrivalchenkov
informatics

zoematthews
mathematics

【问题讨论】:

  • 您的个人资料显示:learning Python at the moment。为什么不使用它?
  • @devnull - 因为有人明确要求我在 bash 中执行此操作。如果有选择,我会在 python 中尝试。
  • 如果你经常被要求在 bash 中做一些事情(从你的previous 问题也可以看出,为什么不尝试学习呢?
  • 你想用 bash 还是 awk 来做?
  • 提问确实是学习的一部分。要求别人为你写不是。您必须尝试一下,然后返回您尝试过的代码,我们会帮助您修复它。

标签: regex replace sed awk


【解决方案1】:

以下管道有效:

sed '2~3!d' A | paste -d $'\n' B - | sed $'3~2i\n'

第一部分告诉 GNU sed 打印第二行,然后是第三行。 paste 将 B 与第一个 sed 的输出合并,使用换行符作为分隔符。最后一行在每对行之后添加换行符。

【讨论】:

    【解决方案2】:

    这个 awk 应该可以工作:

    awk 'FNR==NR{a[i++]=$0;next} NF>0{c++; if (c%2==0) print a[j++] ORS $0 ORS}' fileB fileA
    

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 2021-06-15
      • 2013-12-03
      • 2018-05-19
      • 1970-01-01
      • 2011-07-01
      • 2019-05-14
      • 2011-04-06
      • 2011-03-25
      相关资源
      最近更新 更多