7

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?

5 Answers 5

9

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

a while read loop will "miss" reading the last line if there is no last newline.
1

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

3 Comments

All of these do something but all of them are off target.
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.
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 :))
0

if your purpose is just to cp those files in thelist

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

1 Comment

no different when you do it with shell. shell is calling system command too.
0

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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.