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.
Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.
The echo command writes text to standard output (stdout). The syntax of using the echo command is pretty straightforward: echo [OPTIONS] STRING... Some common usages of the echo command are piping shell variable to other commands, writing text to stdout in a shell script, and redirecting text to a file.
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).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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With