Extract substring using regexp in plain bash

前端 未结 4 1213
清酒与你
清酒与你 2020-11-27 10:52

I\'m trying to extract the time from a string using bash, and I\'m having a hard time figuring it out.

My string is like this:

US/Central - 10:26 PM          


        
4条回答
  •  情话喂你
    2020-11-27 11:17

    Using pure bash :

    $ cat file.txt
    US/Central - 10:26 PM (CST)
    $ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt
    

    another solution with bash regex :

    $ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
        echo ${BASH_REMATCH[1]}
    

    another solution using grep and look-around advanced regex :

    $ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"
    

    another solution using sed :

    $ echo "US/Central - 10:26 PM (CST)" |
        sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'
    

    another solution using perl :

    $ echo "US/Central - 10:26 PM (CST)" |
        perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'
    

    and last one using awk :

    $ echo "US/Central - 10:26 PM (CST)" |
        awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'
    

提交回复
热议问题