在 BASH 中使用文件内容作为命令行参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1674020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using file contents as command line arguments in BASH
提问by Jamie
I'd like to know how to use the contents of a file as command line arguments, but am struggling with syntax.
我想知道如何使用文件的内容作为命令行参数,但我在语法上苦苦挣扎。
Say I've got the following:
说我有以下几点:
# cat > arglist
src/file1 dst/file1
src/file2 dst/file2
src/file3 dst/file3
How can I use the contents of each line in the arglistfile as arguments to say, a cpcommand?
如何使用arglist文件中每一行的内容作为参数来表示cp命令?
回答by matja
the '-n' option for xargs specifies how many arguments to use per command :
xargs 的“-n”选项指定每个命令使用的参数数量:
$ xargs -n2 < arglist echo cp
cp src/file1 dst/file1
cp src/file2 dst/file2
cp src/file3 dst/file3
回答by Stephan202
Using read(this does assume that any spaces in the filenames in arglistare escaped):
使用read(这确实假设文件名中的任何空格arglist都被转义了):
while read src dst; do cp "$src" "$dst"; done < argslist
If the arguments in the file are in the right order and filenames with spaces are quoted, then this will also work:
如果文件中的参数顺序正确并且文件名用空格被引用,那么这也将起作用:
while read args; do cp $args; done < argslist
回答by Aif
回答by ghostdog74
if your purpose is just to cp those files in thelist
如果您的目的只是 cp 列表中的那些文件
$ awk '{cmd="cp "OldIFS=$IFS # Save IFS
$IFS=$'\n' # Set IFS to new line
for EachLine in `cat arglist"`; do
Command="cp $Each"
`$Command`;
done
IFS=$OldIFS
;system(cmd)}' file
回答by NawaMan
Use forloop with IFS(Internal Field Separator) set to new line
使用for循环IFS(内部字段分隔符)设置为new line

