壳牌(bash)的某行前插入文本 [英] Shell (bash) insert text before a certain line

查看:121
本文介绍了壳牌(bash)的某行前插入文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以插入一组线(约5)到一个文件中的第一位的字符串被发现?

例如:

BestAnimals.txt

 

海豚

$插入长颈鹿猫之前BestAnimals.txt> NewBestAnimals.txt

NewBestAnimals.txt

 
长颈鹿

海豚


解决方案

如果使用GNU sed的:

  $猫的动物


海豚
猫$ sed的/ CAT / {N; S /猫\\ N /长颈鹿\\ n&安培; /}动物

长颈鹿

海豚


  1. 搭配一条线(/ CAT /)

  2. 继续下一行(N)

  3. 的插入和匹配的字符串,其中&放替代匹配模式; 重新present匹配的字符串

How can I insert a set of lines (about 5) into a file at the first place a string is found?

For example:

BestAnimals.txt

dog
cat
dolphin
cat

$ "Insert giraffe to BestAnimals.txt before cat" > NewBestAnimals.txt

NewBestAnimals.txt

dog
giraffe 
cat
dolphin
cat

解决方案

If using gnu sed:

$ cat animals
dog
cat
dolphin
cat

$ sed  "/cat/ { N; s/cat\n/giraffe\n&/ }" animals
dog
giraffe
cat
dolphin
cat

  1. match a line with (/cat/)
  2. continue on next line (N)
  3. substitute the matched pattern with the insertion and the matched string, where & represent the matched string.

这篇关于壳牌(bash)的某行前插入文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆