ChatGPT解决这个技术问题 Extra ChatGPT

sed 将带空格的行插入特定行

我在开头有一行空格,例如“Hello world”。我想将此行插入文件中的特定行。例如在下一个文件中插入“hello world”

hello
world

结果:

hello
    hello world
world

我正在使用这个 sed 脚本:

sed -i "${line} i ${text}" $file

问题是我得到了没有空格的新行:

hello
hello world
world

A
Atropo

您可以转义 space 字符,例如添加 2 个空格:

sed -i "${line} i \ \ ${text}" $file

或者您可以在 text 变量的定义中执行此操作:

text="\ \ hello world"

你只能逃出第一个空间。 Sed 似乎可以自动识别其余的空格。例如,a\ text 在前面附加 4 个空格的文本。
a
ashawley

你只需要一个 \ 就可以像这样输入多个空格

sed -i "${line} i \    ${text}" $file

d
devnull
$ a="  some string  "
$ echo -e "hello\nworld"
hello
world
$ echo -e "hello\nworld" | sed "/world/ s/.*/${a}.\n&/" 
hello
  some string  .
world

在上面的替换中添加了 . 以证明保留了尾随的空白。请改用 sed "/world/ s/.*/${a}\n&/"


d
dashohoxha

可以通过像这样拆分表达式来完成:

sed -i $file -e '2i\' -e "     $text"

这是一个 GNU 扩展,用于更轻松地编写脚本。