Formatting date strings in a file with linux bash shell

后端 未结 3 1232
甜味超标
甜味超标 2021-01-23 21:33

When I cat the file an example of the output format is:

ok: servername Mon May 23 00:00:00 EDT 2018
ok: servername Thu Jul 16 00:00:00 EDT 2019

相关标签:
3条回答
  • 2021-01-23 21:55

    When performance matters. Put this in script.awk:

    BEGIN{ 
      m["Jan"]="01"; m["Feb"]="02"; m["Mar"]="03"; m["Apr"]="04"; 
      m["May"]="05"; m["Jun"]="06"; m["Jul"]="07" # to be completed
    }
    {
      print $1, $2, m[$4] "/" $5 "/" $8
    }
    

    Usage: awk -f script.awk logfile

    Output:

    ok: servername 05/23/2018
    ok: servername 07/16/2019
    
    0 讨论(0)
  • 2021-01-23 22:06

    With GNU date, you can specify an input file containing all your date strings; combined with cut and paste:

    paste -d ' ' \
        <(cut -d ' ' -f-2 infile) \
        <(date -f <(cut -d ' ' -f3- infile) '+%m/%d/%Y')
    

    Output:

    ok: servername 05/23/2018
    ok: servername 07/16/2019
    

    This uses process substitution to build a temporary input file for date -f, and for paste to build a new output file.

    0 讨论(0)
  • 2021-01-23 22:12

    According man date, the command is able to

    display time described by STRING, not 'now'

    via --date or -d. So if you store your values in a variable

    DATE="Thu Jul 16 00:00:00 EDT 2019"
    

    you could use something like

    date --date="${DATE}" +%m/%d/%Y
    

    to reformat the timestamp.

    For more information you may have a look into Convert date formats in bash.

    0 讨论(0)
提交回复
热议问题