[英]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. 我想将多行回显到来自grep结果的文件中。
Actually, I'm grep
some text from certain files with command: 事实上,我grep
从命令某些文件一些文字:
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. 借助grep命令的-l
选项,我可以从grep结果中获取文件名。
Now I want to insert multiple lines into file Ah B.cpp Cc
. 现在,我想在文件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. 这将在每个文件上添加文本“ text to prepend
”。
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. 在这里,我们使用while
循环,将每个文件名读取到FILE
变量,并将echo
输出附加到每个文件的末尾。
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
). 对于更高级的情况,您可以使用sed
,该sed
具有特殊的命令( a
和i
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.