使用 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/