Using file contents as command line arguements in

2020-03-18 08:59发布

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 arglist file as arguments to say, a cp command?

标签: bash redirect
5条回答
成全新的幸福
2楼-- · 2020-03-18 09:12

the '-n' option for xargs specifies how many arguments to use per command :

$ xargs -n2 < arglist echo cp

cp src/file1 dst/file1
cp src/file2 dst/file2
cp src/file3 dst/file3
查看更多
虎瘦雄心在
3楼-- · 2020-03-18 09:32

You can use pipe (|) :

cat file | echo

or input redirection (<)

cat < file

or xargs

xargs sh -c 'emacs "$@" < /dev/tty' emacs

Then you may use awk to get arguments:

cat file | awk '{ print $1; }'

Hope this helps..

查看更多
够拽才男人
4楼-- · 2020-03-18 09:33

Using read (this does assume that any spaces in the filenames in arglist are escaped):

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
查看更多
地球回转人心会变
5楼-- · 2020-03-18 09:36

if your purpose is just to cp those files in thelist

$ awk '{cmd="cp "$0;system(cmd)}' file
查看更多
beautiful°
6楼-- · 2020-03-18 09:36

Use for loop with IFS(Internal Field Separator) set to new line

OldIFS=$IFS # Save IFS
$IFS=$'\n' # Set IFS to new line
for EachLine in `cat arglist"`; do
Command="cp $Each"
`$Command`;
done
IFS=$OldIFS
查看更多
登录 后发表回答