select positional argument in xargs
I want to open the location where python is installed. To check the location I used.
whereis python | xargs -n 1 echo
output :
/usr/bin/python3.8
/usr/bin/python3.8-config
/usr/bin/python
/usr/lib/python2.7
/usr/lib/python3.8
/usr/lib/python3.9
/etc/python3.8
/usr/local/lib/python3.8
/usr/include/python3.8
Although I can copy past the location for xdg but I don't want to do it. I want to use pipe operator and open the location using xdg-open
. However, there is one problem. How do I select the argument from the list above. Suppose I want to select the 3rd location. Is there any way to do it.
I thought of following but it did not work.
whereis python | xargs $3 xdg-open
Just filter the output before passing it to xargs:
whereis python | awk '{print $3}' | xargs xdg-open
That awk
command will only print the 3rd word, so that's all you will pass to xargs
. Of course, using xargs
is pointless when you just have a single argument. Perhaps you want this instead?
xdg-open $(whereis python | awk '{print $3}')
Or, simply use which
which will return the first occurrence of the search string in your $PATH
:
xdg-open $(which python)
Note that you cannot open python
with xdg-open
, that's nonsensical since there is no graphical program that can usefully open a binary, let alone a binary that is a scripting language.
I don't think you can do it in xargs - but you could do it with a shell:
whereis python | xargs sh -c 'echo "$3"' sh
However your particular use case doesn't really make sense, as pointed out by vanadium
The purpose of xargs is to give every item of input to a command repeatedly. It does not "select" from the inputs. If you want to do that, you should use other tools like head, tail, grep. For example:
whereis python | fmt -1 | tail -n +3 | head -1