Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a part of the output of a command in Linux Bash?

Tags:

linux

bash

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.

like image 812
William Avatar asked Aug 04 '14 10:08

William


People also ask

How do I copy the output of a command in Linux?

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.

How do you echo the output of a command?

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.


2 Answers

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).
like image 98
Avinash Raj Avatar answered Sep 18 '22 01:09

Avinash Raj


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
like image 45
slavik Avatar answered Sep 18 '22 01:09

slavik