Reputation: 10419
I have a bunch of dates in a logfile that use the day of year format instead of day of month format:
So I see:
2013-10-302
instead of
2013-10-29
I want them in day of month format. So I do:
sed "s/2013-10-302/2013-10-29/
But a problem with this approach is that I have several dates I need to convert. I could do something like if the month is 10, then subtract 273 from the day in year. If the month is 9, subtract something else.
So even if there is no better approach, any tips on how I would just do it this way? i.e. so if is month 10 subtract 273?
Thansk
Upvotes: 1
Views: 455
Reputation: 11703
Try using awk
awk 'BEGIN {
FS=OFS="-"
} {
cmd="date -d "$1"-"$2"-01 +%j";
cmd | getline offset;
$3=sprintf("%02d",$3-offset+1);
print
}' file
Test
Input file
2013-10-302
2013-11-310
2013-09-268
Output
2013-10-29
2013-11-06
2013-09-25
Upvotes: 1
Reputation: 289605
You are getting the date in %Y-%m-%j format, where %j
stands for day of the year.
What if you do this?
$ date -d "Jan 1 2013 + 302 days" "+%F"
2013-10-30
Put it in context, if you have a file like
$ cat a
2013-10-302
You can "clean" it up with the following steps:
$ cat a
2013-10-302
Get the old date and the 3rd field for days since 1 Jan:
$ old_date=$(cat a)
$ echo $old_date
2013-10-302
$ day=$(cut -d- -f3 <<< "$old_date")
$ echo $day
302
Calculate the real date and update the file:
$ new_date=$(date -d "Jan 1 2013 + $day days" "+%F")
$ echo $old_date, $new_date
2013-10-302, 2013-10-30
$ sed -i "s/$old_date/$new_date/g" a
$ cat a
2013-10-30
Upvotes: 1