简体   繁体   中英

How to echo multiple lines into files coming from a grep result

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 Ah B.cpp Cc .

How can I do that ?

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM