Awk solution:
awk '/cat/ && c == 0 {c = 1; print "giraffe"}; {print}' \ BestAnimals.txt
If the animals you want to insert are in "MyOtherBestAnimals.txt", you can also do
awk '/cat/ && c == 0 {c = 1; system("cat MyOtherBestAnimals.txt") }; {print} ' \ BestAnimals.txt
This answer can in principle be broken down as follows, since ; splits awk condition pairs:
/cat/ && c == 0 { c = 1; ... } /cat/ && c == 0 { c = 1; ... } sets c to 1 in the first line containing cat. Then the commands placed in ... are executed, but only once, since c now equal to 1.{print} - print an action without a condition: prints any input line. This is done after the specified pair of conditions of action.
Depending on what is actually on ... , a giraffe is printed, or the contents of "MyOtherBestAnimals.txt" are sent to standard output before printing the first line containing "cat".
Edit
After analyzing the @glenn jackman solution, it seems that this solution can still be improved: when using the input file
nyan cat cat
data is appended to nyan cat , not to a line equal to cat . Then, the solution should query the full string equal to cat :
awk '$0 == "cat" && c == 0 {c = 1; print "giraffe"}; {print}' \ BestAnimals.txt
to insert one row and
awk '$0 == "cat" && c == 0 {c = 1; system("cat MyOtherBestAnimals.txt") }; {print} ' \ BestAnimals.txt
to insert a file
source share