2

I have multiple comma separated files in a folder. Each CSV file looks like following:

"Column1","Date","Column2"
"fdfsd","20151023","rwer"
"fsdsf","20151023","jjfg"
.
.

I need to modify the 2nd Date column to display the date in this format "10/14/2015" or "2015-10-14".

Please can someone help me with this?

Thanks

This is what i have tried:

cat test.csv | while read line ; do echo $line\;$(date -d "%Y%m%d" "+ YYYY/MM/DD") ; done

usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format] "Column1","Date","Column2";

usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format] "fdfsd","20151023","rwer";

usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format] "fsdsf","20151023","jjfg";

3
  • Sorry about not posting earlier. Please have a look. Thanks Commented Oct 26, 2015 at 16:37
  • Can you use perl or awk or python? Commented Oct 26, 2015 at 16:50
  • I can try using awk.. Commented Oct 26, 2015 at 16:57

3 Answers 3

4

Since you just need to insert hyphens into the date, this is a string manipulation problem not a date manipulation problem:

sed -i.bak -re 's/([0-9]{4})([0-9]{2})([0-9]{2})/\1-\2-\3/' *.csv
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this awk to reformat a given date string:

awk 'BEGIN{FS=OFS=","} NR>1{cmd = "date -d \"" $2 "\" \"+%Y-%m-%d\"";
       cmd | getline out; $2=out; close("uuidgen")} 1' file
"Column1","Date","Column2"
"fdfsd",2015-10-23,"rwer"
"fsdsf",2015-10-14,"jjfg"

2 Comments

Hi.. This works great.. Is there way i can use it to just modify the column in the file and not print the entire thing?
It will be: awk 'BEGIN{FS=OFS=","} NR>1{cmd = "date -d \"" $2 "\" \"+%Y-%m-%d\""; cmd | getline out; $2=out; close("uuidgen")} 1' file > _file.tmp && mv _file.tmp file
1

Python has a very robust csv module.

You can do:

$ python -c '
import csv
import datetime
import fileinput

def line_out(line): 
    print ",".join(["\"{}\"".format(e) for e in line])

csv_data=csv.reader(fileinput.input())
line_out(next(csv_data))
for line in csv_data:
    line[1]=datetime.datetime.strptime(line[1], "%Y%m%d").date().isoformat()
    line_out(line)' file

Prints:

"Column1","Date","Column2"
"fdfsd","2015-10-23","rwer"
"fsdsf","2015-10-23","jjfg"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.