【问题标题】:Find line in file and replace it with line from another file在文件中查找行并将其替换为另一个文件中的行
【发布时间】:2021-05-20 04:21:46
【问题描述】:

我的目标是在文件 (file1) 中找到一个字符串,并将其整行替换为另一个文件 (file2) 中特定行的内容(在此示例中为第 3 行)。据我了解,我需要使用 RegEx 来完成第一部分,然后使用第二个 sed 命令来存储 file2 的内容。 sed 绝对不是我的强项,所以我希望这里有人可以帮助一个菜鸟!

到目前为止我有:

sed -i '/^matching.string.here*/s' <(sed '3!d' file2) file1

编辑

示例文件1:

string one
string two
matching.string.here.
string three

示例文件2:

alt string one
alt string two
alt string three

file1 中的预期结果:

string one
string two
alt string three
string three

【问题讨论】:

  • 您能否发布一些来自这两个文件的数据示例以及您预期结果的摘录?

标签: awk sed


【解决方案1】:

您的sed 尝试包含几个无法解释的错误;实际上很难看出您实际上在尝试做什么。

你可能想做一些类似的事情

sed '3!d;s%.*%s/^matching\.string\.here.*/&/%' file2 |
sed -f - -i file1

不清楚您希望/s 是什么意思;你的sed 有这个名字的标志吗?

这会从file2 的第三行创建一个sed 脚本;取出管道到sed -f -,看看生成的脚本是什么样子的。 (如果您的sed 不允许您在标准输入上传递脚本,则必须将其写入临时文件,然后将其传递给第二个sed。)

无论如何,使用 Awk 可能更简单、更健壮。

awk 'NR==3 && NR==FNR { keep=$0; next }
    /^matching\.string\.here/ { $0 = keep } 1' file2 file1

这会将新内容写入标准输出。如果你有 GNU Awk,你可以探索它的-i inplace 选项;否则,您需要将结果写入文件,然后将其移回file1

【讨论】:

    【解决方案2】:

    这可能对你有用(GNU sed):

    sed -n '3s#.*#sed "/matching\\.string\\.here\\./c&" file1#ep' file2
    

    关注 file2 的第 3 行。

    制作一个 sed 脚本,将 file1 中的匹配行更改为焦点所在行的内容并打印结果。

    注意匹配中的句点必须转义两次,以免匹配任意字符。

    【讨论】:

      【解决方案3】:

      这是为awk 量身定制的工作,奖励是您可以避免任何正则表达式:

      awk -v s='matching.string.here' 'FNR == NR {a[FNR] = $0; next} index($0, s) {$0 = a[FNR]} 1' file2 file1
      
      string one
      string two
      alt string three
      string three
      

      更易读的版本:

      awk -v s='matching.string.here' '
      FNR == NR {
         a[FNR] = $0
         next
      }
      index($0, s) {
         $0 = a[FNR]
      } 1' file2 file1
      

      【讨论】:

      • 感谢您的快速回复!但是,当我尝试它输出 file1 的内容而不做任何更改时。您的解决方案究竟在哪里说要使用 file2 的第 3 行?也许我还是不明白,抱歉。
      • 这猜测您想要相应的行,即如果在第 2 行找到 matching.string.here,它将从第一个输入文件中获取第 2 行。
      • $0 = a[FNR] 是它从file2(在这种情况下为#3)抓取相应行的部分。
      猜你喜欢
      • 2014-03-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2023-03-17
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多