Using file contents as command line arguments in BASH

I would like to know how to use the contents of the file as command line arguments, but I am struggling with the syntax.

Say I have 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 a file arglistas arguments, for example, a command cp?

+5
source share
5 answers

The -n option for xargs indicates how many arguments are used for each command:

$ xargs -n2 < arglist echo cp

cp src/file1 dst/file1
cp src/file2 dst/file2
cp src/file3 dst/file3
+7
source

Using read(this assumes that any spaces in the file names are arglistescaped):

while read src dst; do cp "$src" "$dst"; done < argslist

, , :

while read args; do cp $args; done < argslist
+3

You can use pipe (|):

cat file | echo

or input redirection (<)

cat < file

or xargs

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

Then you can use awk to get the arguments:

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

Hope this helps.

+1
source

if your goal is to simply copy these files to a list

$ awk '{cmd="cp "$0;system(cmd)}' file
0
source

Use a loop forwith IFS(Internal Field Separator) set tonew 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
0
source

All Articles