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

后端 未结 4 1989
我寻月下人不归
我寻月下人不归 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
    

提交回复
热议问题