Working With Files in Shell

Inserting Text Before a Certain Line

(taken from SO)

$ cat animals
dog
cat
dolphin
cat

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

sed explained:

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