views:

124

answers:

5

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?

A: 

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..

Aif
no need cat for the awk piece
ghostdog74
All of these do _something_ but all of them are off target.
Jamie
`echo` doesn't read from `stdin`. Besides `cat` doesn't need `echo`. Also, you don't have to redirect into `cat` - this works: `cat file`.
Dennis Williamson
Yes I know, at the very beginning I didn't understand well what he wanted. I tought the output was like "ls", I mean on cols to take less lines. This is why I spoke about shell redirections. (english is not my first language, sorry :))
Aif
+3  A: 

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
Stephan202
+1 Much better than my solution :-D
NawaMan
a while read loop will "miss" reading the last line if there is no last newline.
ghostdog74
+4  A: 

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
matja
A: 

if your purpose is just to cp those files in thelist

$ awk '{cmd="cp "$0;system(cmd)}' file
ghostdog74
Hammers? Nails?
Dennis Williamson
no different when you do it with shell. shell is calling system command too.
ghostdog74
A: 

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
NawaMan
It's not necessary to put the command and its arguments into a variable. Anyway, you'd have to do `$Command` or `\`$Command\`` to make it work.
Dennis Williamson
Thanks, I miss that :D
NawaMan