8

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)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies with the ionCube PHP Loader v4.6.1, Copyright (c) 2002-2014, by ionCube Ltd.

And I only want to output the PHP 5.3.28 (cli) part. How do I do that?

I've tried php -v | grep 'PHP 5.3.28', but that outputs: PHP 5.3.28 (cli) (built: Jun 23 2014 16:25:09) and that's not what I want.

4 Answers 4

10

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).
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

1

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

Comments

0

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}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.