Reputation: 489
I want to echo multiple lines into files coming from a grep result.
Actually, I'm grep
some text from certain files with command:
find . -name *.h -o -name *.c -o -name *.cpp | xargs grep -n -l --color Apache
Output of above command is looks like:
./DIR/A.h
./DIR/B.cpp
./DIR/C.c
With the help of the -l
option of grep command, I can get the file names from the grep result.
Now I want to insert multiple lines into file A.h B.cpp C.c
.
How can I do that ?
Upvotes: 1
Views: 701
Reputation: 396
Try this:
find . -name *.h -o -name *.c -o -name *.cpp | \
xargs grep -n -l --color Apache | \
xargs sed -i '1s/^/text to prepend\n/'
This will prepend text "text to prepend
" on every file.
Upvotes: 3
Reputation: 15214
It depends on the position in file where you want to insert lines. In a simplest case you could just append them to the end:
find . -name '*.h' -o -name '*.c' -o -name '*.cpp' |
xargs grep -n -l |
while read FILE; do echo -e "line1\nline2" >>"$FILE"; done
Here we are using while
loop that reads each file name to FILE
variable and append echo
output to the end of each file.
Update: for inserting to the beggining of the files:
find . -name '*.h' -o -name '*.c' -o -name '*.cpp' |
xargs grep -n -l |
while read FILE; do (echo -e "line1\nline2"; cat "$FILE") >>"$FILE.new" && mv "$FILE.new" "$FILE"; done
For more advanced cases you could use sed
that have a special commands for that (a
and i
).
Upvotes: 1