将行插入多个指定的文件

时间:2013-11-12 05:53:04

标签: linux shell sed

我想在多个指定类型文件的开头插入一行,文件位于当前目录或子目录中。

我知道使用

find . -name "*.csv"

可以帮助我列出我想用于插入的文件。

并使用

sed -i '1icolumn1,column2,column3' test.csv

可以用来在文件的开头插入一行

但现在我不知道如何将文件名从“find”命令传递到“sed”命令。

有人可以给我任何建议吗?

或者有更好的解决方案吗?

顺便说一句,在一行命令中这样做是否可行?

1 个答案:

答案 0 :(得分:2)

这样:

find . -type f -name "*.csv" -exec sed -i '1icolumn1,column2,column3' {} +

-exec在这里做所有的魔法。 man find的相关部分:

   -exec command ;
   Execute  command;  true  if  0  status  is returned.  All following arguments
   to find are taken to be arguments to the command until an argument consisting
   of `;' is encountered.  The string `{}' is replaced by the current file name
   being processed everywhere it occurs in the arguments to the command, not just
   in arguments where it is alone, as in some versions  of find.   Both  of  
   these constructions might need to be escaped (with a `\') or quoted to protect
   them from expansion by the shell.  See the EXAMPLES section for examples of
   the use of the -exec option.  The specified command is run once for each
   matched file.  The command is executed in the starting directory.   There
   are unavoidable security  problems  surrounding use of the -exec action;
   you should use the -execdir option instead