macos - 使用 bash 脚本在文件中添加多行

标签 macos bash sed

使用 bash 脚本,我试图在文件中插入一行(最终会有 4 行,一行接一行)。

我正在尝试实现 iiSeymour 对线程的回答:

Insert lines in a file starting from a specific line

我认为这与 dgibbs 在他自己的线程中发表的评论相同:

Bash: Inserting a line in a file at a specific location

我要插入新文本的那一行很长,所以我先把它保存在一个变量中:

field1=$(head -2 file847script0.xml | tail -1)

我要插入的文字是:

insert='newtext123'

运行时:

sed -i".bak" "s/$field1/$field1\n$insert/" file847script0.xml 

我得到错误:

sed: 1: "s/<ImageAnnotation xmln ...": bad flag in substitute command: 'c'

我也试过跟帖

sed throws 'bad flag in substitute command'

但是命令

sed -i".bak" "s/\/$field1/$field1\n$insert/" file847script0.xml

仍然给我同样的错误:

sed: 1: "s/\/<ImageAnnotation xm ...": bad flag in substitute command: 'c'

我使用的是 Mac OS X 10.5。

知道我做错了什么吗?谢谢!

最佳答案

天哪,就用awk吧。无需担心替换文本中的特殊字符或随机单字符命令和标点符号。

在这种情况下,您似乎只需要在第 2 行之后打印一些新文本,这样就可以了:

$ cat file
a
b
c

$ insert='absolutely any text you want, including newlines
slashes (/), backslashes (\\), whatever...'

$ awk -v insert="$insert" '{print} NR==2{print insert}' file
a
b
absolutely any text you want, including newlines
slashes (/), backslashes (\), whatever...
c

关于macos - 使用 bash 脚本在文件中添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745253/

相关文章:

linux - 如何添加一行或用 awk 或 sed 替换第一行

macos - 如何将 NSWindow 绑定(bind)到另一个 NSWindow?

bash - 从文本文件中解析出必要的部分

bash - 遍历子目录并对某些文件执行 awk 脚本

bash - for 循环中 bash 中的简单数学语句

regex - 如何用通用电子邮件地址替换一组文件中的所有电子邮件地址

linux - Mac 上的 sed 未按预期更新文件

c++ - OpenCV 中的 GStreamer 不通过 UDP 发送视频数据

c++ - OSX OpenGL 4.1 glEnableVertexAttribArray glDrawArrays GL_INVALID_OPERATION

macos - Apache 2.2 本地主机 VirtualHosts 问题