比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
比如说,我有一个文件foo.txt,指定了N个参数
arg1
arg2
...
argN
我需要传递给命令my_command
如何使用文件的行作为命令的参数?
当前回答
在我的bash shell下面的工作就像一个魅力:
cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'
input_file在哪里
arg1
arg2
arg3
显然,这允许您对input_file中的每一行执行多个命令,这是我在这里学到的一个不错的小技巧。
其他回答
如果你的shell是bash, $(cat afile)的快捷方式是$(< afile),所以你可以这样写:
mycommand "$(< file.txt)"
bash手册页中的“命令替换”部分中有详细说明。
或者,让你的命令从stdin读取,这样:mycommand < file.txt
你可以使用反勾:
echo World > file.txt
echo Hello `cat file.txt`
这两种解决方案即使在行中有空格时也有效:
readarray -t my_args < foo.txt
my_command "${my_args[@]}"
如果readarray不起作用,用mapfile代替它,它们是同义词。
我以前尝试过下面这个,但当my_command是一个脚本时有问题:
xargs -d '\n' -a foo.txt my_command
command `< file`
将文件内容传递给stdin上的命令,但将删除换行符,这意味着您不能单独遍历每一行。为此,你可以写一个带有' For '循环的脚本:
for line in `cat input_file`; do some_command "$line"; done
或者(多行变体):
for line in `cat input_file`
do
some_command "$line"
done
或者(多行变体,用$()代替' '):
for line in $(cat input_file)
do
some_command "$line"
done
引用:
对于循环语法:https://www.cyberciti.biz/faq/bash-for-loop/
在我的bash shell下面的工作就像一个魅力:
cat input_file | xargs -I % sh -c 'command1 %; command2 %; command3 %;'
input_file在哪里
arg1
arg2
arg3
显然,这允许您对input_file中的每一行执行多个命令,这是我在这里学到的一个不错的小技巧。