1

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

我知道使用

find . -name "*.csv"

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

并使用

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

可用于在文件开头插入一行,

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

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

或者有没有更好的解决方案来做到这一点?

顺便说一句,在一行命令中执行此操作是否有效?

4

2 回答 2

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
于 2013-11-12T05:54:33.883 回答
2

尝试使用xargs将输出find和命令行参数传递给下一个命令,在这里sed

find . -type f -name '*.csv' -print0 | xargs -0 sed -i '1icolumn1,column2,column3'

另一种选择是-exec使用find.

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

注意:据观察,这xargs是一种更有效的方式,可以使用-P选项处理多个进程。

于 2013-11-12T05:56:09.870 回答