I have a script. myScript.

It takes two args. myScript arg1 arg2.

Let's say I have three sets of arguments.

argA1 argB1
argA2 argB2
argA3 argB3

Is there a way to pipe each line to myScript. I am open to having the set of args in a file, maybe use xargs. Not certain what to investigate.

So I would run command like faux example below:

cat myFile | xargs > myScript

Not to have another script, just commands on command line.



xargs -l1 <myFile myScript

-l1 tells xargs to run myScript once for each 1 line of input, with the words on that 1 line passed as separate arguments.

For xargs, words are separated with whitespace, and you can still have whitespace (even newlines) in a words by using quoting. Note however that while xargs supports "...", '...' and \ for quoting like most shells, its parsing is different from that of Bourne-like shells. In particular, there's no backslash processing in neither "..." nor '...' and only \ can escape a newline.

For for instance, myFile could contain:

word1.1 word1.2
"word 2.1" 'word 2.2'
"word'3.1" 'word"3.2'
'word"'"4'1" word\"4\'2
'word '\
5.1 "word "\


xargs -l1 <myFile printf 'First word: "%s", second word: "%s"\n'

would produce:

First word: "word1.1", second word: "word1.2"
First word: "word 2.1", second word: "word 2.2"
First word: "word'3.1", second word: "word"3.2"
First word: "word"4'1", second word: "word"4'2"
First word: "word
5.1", second word: "word

With the GNU implementation of xargs, you can improve it to:

xargs -l1 -r -a myFile myScript

Which has the benefit of leaving stdin alone and of not running myScript if myFile is empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.