使用Bash在特定行之前插入文本 [英] Insert text before a certain line using Bash
本文介绍了使用Bash在特定行之前插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在第一行找到的字符串中插入一组行(大约5条)?
How can I insert a set of lines (about 5) into a file at the first place a string is found?
例如:
BestAnimals.txt
BestAnimals.txt
dog
cat
dolphin
cat
$将长颈鹿插入猫的BestAnimals.txt中"> NewBestAnimals.txt
$ "Insert giraffe to BestAnimals.txt before cat" > NewBestAnimals.txt
NewBestAnimals.txt
NewBestAnimals.txt
dog
giraffe
cat
dolphin
cat
推荐答案
如果使用gnu sed:
If using gnu sed:
$ cat animals
dog
cat
dolphin
cat
$ sed "/cat/ { N; s/cat\n/giraffe\n&/ }" animals
dog
giraffe
cat
dolphin
cat
- 用(/cat/)匹配一行
- 继续下一行(N)
- 用插入和匹配的字符串替换匹配的模式,其中
&
代表匹配的字符串.
- match a line with (/cat/)
- continue on next line (N)
- substitute the matched pattern with the insertion and the matched string, where
&
represent the matched string.
这篇关于使用Bash在特定行之前插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文