简体   繁体   中英

SED, AWK: Change Date Format

Good Day, I'm a little bit new and confused about replacing the date. I want to change all of dates in a huge file from

21/3/2016

to

2016-03-21T00:00:00.008Z

I did something like this

sed -ri 's#([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})#date -d"\1/\2/\3"
+"%Y-%m-%dT%H:%M:%SZ"#e' file

and it creates a file but no content. Thanks advance

With GNU sed:

echo "21/1/2016" | sed -E 's|/([1-9])/|/0\1/|; s|^([1-9]/)|0\1|; s|([0-9]{2})/([0-9]{1,2})/([0-9]{4})|\3-\2-\1T00:00:00.008Z|'

Output:

2016-03-21T00:00:00.008Z

Just use awk:

$ awk -F'/' '{printf "%04d-%02d-%02dT00:00:00.008Z\n", $3, $2, $1}' file
2016-03-21T00:00:00.008Z

In awk:

$ awk '{
    split($0,a,"/")                            # split by / to a
    for(i=1;i<=2;i++)             
        a[i]=sprintf("%02d", a[i])             # zeropad a[1] and a[2]
    print a[3]"-"a[2]"-"a[1] "T00:00:00.008Z"  # output
}' file
2016-03-21T00:00:00.008Z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM