Baa*_*rud 4 command-line bash shell-script
我有一个包含一长串文件名(带有完整路径)的文件。我还有一个我想多次运行的程序,使用此列表中的一个和一个文件名作为参数。我想运行的程序很遗憾是一个自制的脚本;所以它一次只能取一个文件名,并且它不能接受来自stdin 的输入(如文件名列表)——所以不可能进行管道或输入重定向。
我需要的是一个命令,它将运行另一个命令(我的脚本),使用文件中的行作为参数。
喜欢的东西find
与-exec
-action ...( find . -name "*.txt" -exec command \;
)。我想我实际上可以find
在这里使用,但我希望对输入文件进行排序......
所以我需要的是这样的:
for_each_command1 -f list_of files -c './my_command {}' for_each_command2 -f list_of_files -exec ./my_command {} \; for_each_command3 -c './my_command {}'我处理此类任务的常用方法是
$ wc -l list_of_files 232 $ for (( i=1; 我愿意 > ./my_command "`sed -n "${i}p" list_of_files`" > 完成sed
- 不幸的是,有很多开销而且它并不漂亮(但它确实有效......):
那么是否有内置的命令或 shell 来处理这样的事情?
方便地,xargs -I
正是你想要的:
$ xargs <my_file_list.txt -I filename ./my_command "filename"
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)-I replace-str Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1.
这意味着它只需要一个以换行符分隔的输入行,并将其作为单个参数调用您的命令。除了换行符之外,没有任何东西被视为分隔符,因此空格和其他特殊字符都可以。
请注意,如果您想在文件名中允许换行,则 nul 终止符(根据通配符的答案)也可以在文件中使用。
小智 3
我假设您的文件列表存储在名为“filelist.txt”的文件中,每个文件名位于一行中。然后您可以使用每一行作为参数来调用脚本,如下所示:
while read name; do
./yoursrcipt.sh "$name"
done <filelist.txt
Run Code Online (Sandbox Code Playgroud)