bash 将文本插入特定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3273670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:20:37  来源:igfitidea点击:

inserting text into a specific line

bash

提问by user349418

I've got a text file, and using Bash I wish to insert text into into a specific line.

我有一个文本文件,我希望使用 Bash 将文本插入到特定行中。

Text to be inserted for example is !comment: http://www.test.cominto line 5

例如,要插入的文本是!comment: http://www.test.com第 5 行

!aaaa
!bbbb
!cccc
!dddd
!eeee
!ffff

becomes,

变成,

!aaaa
!bbbb
!cccc
!dddd
!comment: http://www.test.com
!eeee
!ffff

回答by Anders

sed '4a\
!comment: http://www.test.com' file.txt > result.txt

i inserts before the current line, a appends after the line.

i 在当前行之前插入,在该行之后追加 a。

回答by ghostdog74

you can use awk as well

你也可以使用 awk

$ awk 'NR==5{
# cf. http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed
line='!comment: http://www.test.com'
#printf '%s\n' H '/!eeee/i' "$line" . wq | ed -s file
printf '%s\n' H 5i "$line" . wq | ed -s file
="!comment: http://www.test.com\n"##代码##}1' file !aaaa !bbbb !cccc !dddd !comment: http://www.test.com !eeee !ffff

回答by HymanIT

Using man 1 ed (which reads entire file into memory and performs in-place file editing without previous backup):

使用 man 1 ed(将整个文件读入内存并在没有先前备份的情况下执行就地文件编辑):

##代码##