【问题标题】:Replace line with file content using sed使用 sed 将行替换为文件内容
【发布时间】:2022-01-05 23:00:14
【问题描述】:

我正在尝试用另一个文件的内容替换文件中的一行,并打印结果。

#!/bin/sh

set -e

echo "a
b
c" > template.txt
echo "Hello, World!" > foo.txt

sed -e '/b/ {
  d
  r /dev/stdin
}' "template.txt" < "foo.txt"

不幸的是,这会导致

a
c

当我删除 sed 脚本中的 d 行时,我可以得到

a
b
Hello, World
c

如何摆脱b 并保留Hello, World

【问题讨论】:

    标签: sed sh


    【解决方案1】:

    感谢 ToxicFrog 的回答。显然,d 的意思是“清除模式空间并立即进入下一行”,所以我需要以相反的顺序执行这些命令。 r 立即将文件内容附加到输出中,而不是将其读入模式空间。

    sed -e '/b/ {
      r /dev/stdin
      d
    }' "template.txt" < "foo.txt"
    

    【讨论】:

      【解决方案2】:

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

      sed '/b/cHello World!' file
      

      将包含b 的任何行更改(c) 为Hello World!

      【讨论】:

        猜你喜欢
        • 2020-10-31
        • 2017-12-17
        • 1970-01-01
        • 1970-01-01
        • 2018-10-09
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多