Thursday, January 3, 2008

iCal filtering

I wanted to pull out just the 2008 entries from a calendar in iCal (ics) format, and import those into a calendar of my own.

At first, I went looking for an IcsToCsv converter (click on Attachments to see the Python code; there's Ruby code for ics2csv too). My plan was to use grep to match the 2008 lines after the CSV format put the entire entry on one line. Next I realized that it was much easier to use Smultron for the CSV conversion since all the event entries were uniform.

Then I noticed I could go straight to the end game, without CSV, with judicious use of grep to include context before and after the match ...

grep -B 1 -A 4 "DTSTART:2008" Exported.ics

So the Sample file I wanted to import could be created this way:

sed -n '/^BEGIN:VCALENDAR/,/^BEGIN:VEVENT/p' Exported.ics | sed '$d' > Sample.ics

grep -B 1 -A 4 "^DTSTART:2008" Exported.ics | grep -v -- "--" >> Sample.ics

tail -5 Exported.ics | sed -n '/^END:VEVENT/,/^END:VCALENDAR/p' | sed '1d' >> Sample.ics

The middle command is the good one; the first and last commands are safer to do visually because they assume that all of the iCal events are formatted just like the ones I scanned ... and it can be dangerous to assume that much!

If you have problems importing, check the line endings. On my Mac, I ended up with ^M (as seen with the vis command, or with cat -etv). You can remove those with this command:

cat Sample.ics | tr -s '\r' '\n' > Clean.ics

(If you want to preserve blank lines, don't use -s.) My import went fine. I love my command line text manipulation tools!

No comments:

Post a Comment