Insert text before a certain line using Bash

前端 未结 5 1448
时光说笑
时光说笑 2020-12-17 04:24

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         


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 04:45

    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.

提交回复
热议问题