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

后端 未结 4 1983
我寻月下人不归
我寻月下人不归 2021-02-06 16:08

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         


        
相关标签:
4条回答
  • 2021-02-06 16:31

    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
    
    0 讨论(0)
  • 2021-02-06 16:33

    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
    
    0 讨论(0)
  • 2021-02-06 16:35

    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).
    0 讨论(0)
  • 2021-02-06 16:41

    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}'
    
    0 讨论(0)
提交回复
热议问题