15

I'm on Ubuntu. I copied some arguments (separated by newline) and I can use xsel to print them out like this

$ xsel
arg1
arg2
arg3
arg4
...

Now, I want to use each of these arguments for another command and execute that command as many times as there are arguments.

So I tried

$ xsel | mycommand "constantArgument" 1ドル

However, this executed mycommand only for the first argument. How can I execute it for every argument?

asked Mar 19, 2014 at 19:59
1
  • Edited the question to reflect the fact that there is more than one argument to mycommand. Commented Mar 19, 2014 at 20:10

3 Answers 3

15

You can simply use xargs

xsel | xargs -n1 echo mycommand 

-n1 means one arg for mycommand, but it's just dry run, it will show what going to be run, to run it remove echo

For constant Argument

xsel | xargs -I {} -n1 echo mycommand "constantArgument" {}
answered Mar 19, 2014 at 20:06
3
  • 1
    What if "mycommand" expects more than one argument out of which the xsel contains just one argument? Commented Mar 19, 2014 at 20:07
  • xsel | xargs -n1 echo mycommand -more-arg Commented Mar 19, 2014 at 20:08
  • xsel | xargs -n2 echo mycommand two arg per command Commented Mar 19, 2014 at 20:09
7
xsel | while read line; do mycommand "$line"; done

Or something similar. You can also use xargs, which is a very powerful command for manipulation of command line arguments.

answered Mar 19, 2014 at 20:02
1

For a little customizability:

printf "${CMD} %s ${ARG2}\n" `xsel` | sh -n

You can remove the -noexecute flag after you've seen how it works.

If it works for you, you can drop sh entirely and do this instead:

. <<HERE /dev/stdin
 $(printf "${CMD} %s ${ARG2}\n" `xsel`)
HERE

Or faster:

printf "${CMD} %s ${ARG2}\n" `xsel` | . /dev/stdin

Either way is easy and will do it.

answered Mar 20, 2014 at 9:45

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.