Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

date - how to convert 23/1/17 to 23/01/2017 in a row of csv file with unix?

I am looking for how to convert all dates in a csv file row into this format ? example I want to convert 23/1/17 to 23/01/2017

I use unix

thank you

my file is like this :

23/1/17 17/08/18 1/1/2 5/6/03 18/05/2019

and I want this :

23/01/2017 17/08/2018 01/01/2002 05/06/2003 18/05/2019


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I used date_samples.csv as my test data:

23/1/17,17/08/18,1/1/02,5/6/03,18/05/2019

cat date_samples.csv | tr "," "
" | awk 'BEGIN{FS=OFS="/"}{print $2,$1,$3}' | 
while read CMD; do
    date -d $CMD +%d/%m/%Y >> temp
done; cat temp | tr "
" "," > converted_dates.csv ; rm temp; truncate -s-1 converted_dates.csv

Output:

23/01/2017,17/08/2018,01/01/2002,05/06/2003,18/05/2019

This portion of the code converts your "," to new lines and makes your input DD/MM/YY to MM/DD/YY, since the date command does not accept date inputs of DD/MM/YY. It then loops through re-arranged dates and convert them to DD/MM/YYYY format and temporarily stores them in temp.

cat date_samples.csv | tr "," "
" | awk 'BEGIN{FS=OFS="/"}{print $2,$1,$3}' | 
while read CMD; do
    date -d $CMD +%d/%m/%Y >> temp
done;

This line cat temp | tr " " "," > converted_dates.csv ; rm temp; truncate -s-1 converted_dates.csv converts the new line back to "," and puts the output to converted_dates.csv and deletes temp.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...