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– Wes2014年03月19日 20:10:03 +00:00Commented Mar 19, 2014 at 20:10
3 Answers 3
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" {}
-
1What if "mycommand" expects more than one argument out of which the xsel contains just one argument?Wes– Wes2014年03月19日 20:07:20 +00:00Commented Mar 19, 2014 at 20:07
-
xsel | xargs -n1 echo mycommand -more-arg
Rahul Patil– Rahul Patil2014年03月19日 20:08:04 +00:00Commented Mar 19, 2014 at 20:08 -
xsel | xargs -n2 echo mycommand
two arg per commandRahul Patil– Rahul Patil2014年03月19日 20:09:03 +00:00Commented Mar 19, 2014 at 20:09
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.
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.