How do I get a part of the output of a command in Bash?
For example, the command php -v
outputs:
PHP 5.3.28 (cli) (built: Jun 23 2014 16:25:09
a classic "million ways to skin a cat" question...
These methods seem to filter by spaces... If the versions/notes contain spaces, this fails.
The (
brackets, however, seem consistent across all my platforms so I've used the following:
For example, on Debian:
root@host:~# php -v | head -1
PHP 5.3.28-1~dotdeb.0 with Suhosin-Patch (cli) (built: Dec 13 2013 01:38:56)
root@host:~# php -v | head -1 | cut -d " " -f 1-2
PHP 5.3.28-1~dotdeb.0
So here I trim everything before the second (
:
root@host:~# php -v | head -1 | cut -d "(" -f 1-2
PHP 5.3.28-1~dotdeb.0 with Suhosin-Patch (cli)
Note: there will be a trailing white-space (blank space at the end)
Alternatively, you could always use your package manager to determine this (recommended):
root@debian-or-ubuntu-host:~# dpkg -s php5 | grep 'Version'
Version: 5.3.28-1~dotdeb.0
...or on a CentOS, Red Hat Linux, or Scientific Linux distribution:
[root@rpm-based-host ~]# rpm -qa | grep php-5
php-5.4.28-1.el6.remi.x86_64
In pure Bash you can do
echo 'PHP 5.3.28 (cli) (built: Jun 23 2014 16:25:09)' | cut -d '(' -f 1,2
Output:
PHP 5.3.28 (cli)
Or using space as the delimiter:
echo 'PHP 5.3.28 (cli) (built: Jun 23 2014 16:25:09)' | cut -d ' ' -f 1,2,3
You could try the below AWK command,
$ php -v | awk 'NR==1{print $1,$2,$3}'
PHP 5.3.28 (cli)
It prints the first three columns from the first line of input.
NR==1
(condition)ie, execute the statements within {}
only if the value of NR variable is 1.{print $1,$2,$3}
Print col1,col2,col3. ,
in the print statement means OFS (output field separator).If you want all the lines that contain "php", do this:
$ php -v | grep -i "php"
Then if you want the first three words within those, you can add another pipe as @Avinash suggested:
$ php -v | grep -i "php" | awk 'NR==1{print $1,$2,$3}'