【问题标题】:Add multiple lines in file using bash script使用 bash 脚本在文件中添加多行
【发布时间】:2014-09-04 21:13:18
【问题描述】:

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

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

【问题讨论】:

  • 我怀疑插入的字段文本破坏了 sed 模式匹配语法,如果其中有一个“/”(如果它是 HTML,也可能有),那么它会破坏。您可以尝试其他模式匹配字符,例如:sed "s|$field...|..." ...
  • 命令 sed -i".bak" "s|$field1|$field1\n$insert|" file847script0.xml 插入该行,但不将 \n 识别为新行。我该如何解决?谢谢!

标签: macos bash sed


【解决方案1】:

按行号不是更容易吗?如果您知道它是第二行或第 n 行(如果您是模式匹配,grep 会告诉您行号),那么您可以简单地使用 sed 找到正确的行,然后追加一个新行(或 4 个新行)。

cat <<EOF > testfile
one two three
four five six
seven eight nine
EOF

sed -re '2a\hello there' testfile

会输出

one two three
four five six
hello there
seven eight nine

【讨论】:

  • 我实际上设法在特定行插入了一个新行,但它不会“推”整个文本。我会在同一行中获取新文本和旧文本。
  • 好吧,我做到了。我猜你在 sed 中使用的是“i”命令而不是“a”命令? OSX 上的 sed 与 Linux 机器通常安装的 GNU sed 不太一样。也许有区别。我没有 OSX 可供测试。
  • 我实际上是在使用 sed -i".bak" '3a\ new line' file.xml。我试过你的答案,但 -re 选项是“非法的”。我懂了;是的,我学的不一样。。谢谢!
  • 也许这与 OSX 的 sed 有所不同...您可以尝试: ```` sed '3a\ new line' file.xml ``` -- 在 ` 后面加回车3a`
  • 是的,这就是我尝试和工作的;即:插入文本,但在之前有文本的行中,插入的文本就在旧文本之前...再次感谢!
【解决方案2】:

很抱歉,请使用 awk。无需担心替换文本中的特殊字符或随机的单字符命令和标点符号。

在这种情况下,您似乎只需要在第二行之后打印一些新文本,那就是:

$ 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

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多