在特定行号插入文本

The*_*age 16 shell-script text-processing

我正在编写一个 bash 脚本,它将根据行中的数据拆分文本文档的内容。

如果原始文件的内容是

01 line
01 line
02 line
02 line
Run Code Online (Sandbox Code Playgroud)

如何使用 bash 插入此文件的第 3 行以导致

01 line
01 line
text to insert
02 line
02 line
Run Code Online (Sandbox Code Playgroud)

我希望在我的脚本中使用 heredoc 或类似的东西来做到这一点

#!/bin/bash

vim -e -s ./file.txt <<- HEREDOC
    :3 | startinsert | "text to insert\n"
    :update
    :quit
HEREDOC
Run Code Online (Sandbox Code Playgroud)

以上当然不起作用,但是我可以在此 bash 脚本中实施任何建议吗?

Ste*_*nny 19

您可以ex按行号使用 POSIX 工具:

ex a.txt <<eof
3 insert
Sunday
.
xit
eof
Run Code Online (Sandbox Code Playgroud)

或字符串匹配:

ex a.txt <<eof
/Monday/ insert
Sunday
.
xit
eof
Run Code Online (Sandbox Code Playgroud)

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html


thr*_*rig 10

sed 将是一个传统的选择(GNU sed 可能有比这更简单的形式)。

$ cat input
01 line
01 line
02 line
02 line
$ sed '2a\
text to insert
' < input
01 line
01 line
text to insert
02 line
02 line
$ 
Run Code Online (Sandbox Code Playgroud)

或者,非常传统,ed(奖励!没有不可移植sed -i形式的就地编辑)。

$ (echo 2; echo a; echo text to insert; echo .; echo wq) | ed input
32
01 line
47
$ cat input
01 line
01 line
text to insert
02 line
02 line
$ 
Run Code Online (Sandbox Code Playgroud)

(这与 无关bash。)

  • 添加了 bonux 用 `cat file-to-insert.txt` 替换了 `echo text to insert` (2认同)

小智 8

$ awk 'NR==3{print "text to insert"}1' a.txt
01 line
01 line
text to insert
02 line
02 line
Run Code Online (Sandbox Code Playgroud)


小智 7

怎么样:

head -n 2 ./file.txt > newfile.txt
echo "text to insert" >> newfile.txt
tail -n +3 ./file.txt >> newfile.txt
mv newfile.txt file.txt
Run Code Online (Sandbox Code Playgroud)

  • 奇怪但有趣的想法+1 (2认同)