Formatting date strings in a file with linux bash shell

冷暖自知 提交于 2020-05-09 09:44:12

问题


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

I would like the format to be something like

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

I need to use the Linux bash shell to do it. If any one could help me I be very grateful.


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/61015078/formatting-date-strings-in-a-file-with-linux-bash-shell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!