So, a few days ago at work I had this problem, I had a file containing many lines of dates in the following format:
mm-dd-yyyy but I had to convert it to yyyy-mm-dd and then join the sed and it’s arguments in a shell script (but I will not cover this shell script today, it is out of focus here).
To solve my problem, I just did the following:
#sed -e “s_\(..\)\-\(..\)\-\(….\)_\3-\1-\2_” sample.txt
Once I did it, I had my date format converted to the new one and sent to the output. So if you want it to be inserted in a new file, just add “>” after the file name, just like this:
#sed -e “s_\(..\)\-\(..\)\-\(….\)_\3-\1-\2_” sample.txt > sample_new.txt
Now you’ve got a new file containing ALL the lines in the new format! 😀
References:
http://www.grymoire.com/Unix/Sed.html
2 responses to “Editing date format with sed”
sri
October 17th, 2013 at 17:31
Hi i have a tsv file which has some columns and in those columns i have 2 fields with mm/dd/yyyy format and i need to convert it to yyyy/mm/dd format . how would i do that
Ryan Meldrum
February 25th, 2015 at 17:31
Saw this and this was exactly the opposite of what I needed, but it formed the basis of what I wanted. This is the final form of the sed command I ended up with. Thanks!
sed -e ‘s_\([0-9]\{4\}\)\-\([0-9]\{2\}\)\-\([0-9]\{2\}\)_\2/\3/\1_g’