Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
Edited the question to reflect the fact that there is more than one argument to mycommand. –  Wes Mar 19 at 20:10

3 Answers 3

up vote 11 down vote accepted

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" {}
share|improve this answer
    
What if "mycommand" expects more than one argument out of which the xsel contains just one argument? –  Wes Mar 19 at 20:07
    
xsel | xargs -n1 echo mycommand -more-arg –  Rahul Patil Mar 19 at 20:08
    
xsel | xargs -n2 echo mycommand two arg per command –  Rahul Patil Mar 19 at 20:09
    
Thanks. This is useful. –  Wes Mar 19 at 20:12
    
You are most welcome, don't forgot to accept answer if you find it useful. –  Rahul Patil Mar 19 at 20:13
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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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