11

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?

  • Edited the question to reflect the fact that there is more than one argument to mycommand. – Wes Mar 19 '14 at 20:10
12

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" {}
  • What if "mycommand" expects more than one argument out of which the xsel contains just one argument? – Wes Mar 19 '14 at 20:07
  • xsel | xargs -n1 echo mycommand -more-arg – Rahul Patil Mar 19 '14 at 20:08
  • xsel | xargs -n2 echo mycommand two arg per command – Rahul Patil Mar 19 '14 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.

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.

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.