Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text before a certain line using Bash

Tags:

bash

shell

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
like image 603
Pez Cuckow Avatar asked Dec 02 '22 21:12

Pez Cuckow


1 Answers

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.
like image 154
Fredrik Pihl Avatar answered Dec 20 '22 09:12

Fredrik Pihl