0
168,1331122362,412482,,111,,3654

I have the above csv, the second column being a timestamp. I need to convert that timestamp to datetime format which i'm using the following awk statement:

awk -i inplace -F"," '{OFS=","; $2=strftime("%Y-%m-%d %H:%M:%S", $2);}' file.csv

If I remove the inplace option and add a 'print$0' it works as I expect it to work but when doing it with the inplace option it just empties my csv file. I have been looking around and haven't found anyone with similar problems so i'm assuming there is something wrong with my statement but I can't figure out what it is. Probably since i'm not familiar with awk/sed at all.

4

When using -i inplace with GNU awk, you will do in-place editing of the given file. It is the output of the awk program that is written back into the file. If your awk program does not output anything, the file will be emptied (this is also how sed -i works with GNU sed).

You should therefore use

awk -i inplace -F ',' '{ OFS=","; $2 = strftime("%Y-%m-%d %H:%M:%S", $2); print }' file.csv

or, to avoid setting OFS for each input line,

awk -i inplace -F ',' -v OFS=',' '{ $2 = strftime("%Y-%m-%d %H:%M:%S", $2); print }' file.csv

or, shorter,

awk -i inplace -F ',' -v OFS=',' '{ $2 = strftime("%F %T", $2) }; 1' file.csv

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.