Parse Date in Bash

前端 未结 10 1615
灰色年华
灰色年华 2020-11-29 02:17

How would you parse a date in bash, with separate fields (years, months, days, hours, minutes, seconds) into different variables?

The date format is: YYYY-MM-D

相关标签:
10条回答
  • 2020-11-29 02:55

    The array method is perhaps better, but this is what you were specifically asking for:

    IFS=" :-"
    read year month day hour minute second < <(echo "YYYY-MM-DD hh:mm:ss")
    
    0 讨论(0)
  • 2020-11-29 02:57

    have you tried using cut? something like this: dayofweek=date|cut -d" " -f1

    0 讨论(0)
  • 2020-11-29 02:59

    This is simple, just convert your dashes and colons to a space (no need to change IFS) and use 'read' all on one line:

    read Y M D h m s <<< ${date//[-:]/ }
    

    For example:

    $ date=$(date +'%Y-%m-%d %H:%M:%S')
    $ read Y M D h m s <<< ${date//[-: ]/ }
    $ echo "Y=$Y, m=$m"
    Y=2009, m=57
    
    0 讨论(0)
  • 2020-11-29 02:59

    Pure Bash:

    date="2009-12-03 15:35:11"
    saveIFS="$IFS"
    IFS="- :"
    date=($date)
    IFS="$saveIFS"
    for field in "${date[@]}"
    do
        echo $field
    done
    
    2009
    12
    03
    15
    35
    11
    
    0 讨论(0)
提交回复
热议问题