Wednesday, November 14, 2007

Sort a File by a Defined Delimiter

I was sorting out a few colon delimited files tonight. I though the task might be post worthy. The two examples below are colon, ":", delimited and pipe, "|", delimited. Obviously, you can define other types of delimiters such as "," , ";" , "#", and etc.

# vi sortme
phoenix:az:mountain
los angeles:ca:pacific
augusta:me:eastern
houston:tx:central
dallas:tx:central
berkeley:ca:pacific
seattle:wa:pacific
denver:co:mountain
santa fe:nm:mountain
:wq!

Sort by TZ
# sort -t: +2 sortme
dallas:tx:central
houston:tx:central
augusta:me:eastern
denver:co:mountain
phoenix:az:mountain
santa fe:nm:mountain
berkeley:ca:pacific
los angeles:ca:pacific
seattle:wa:pacific

Sort by state
# sort -t":" +1 sortme
phoenix:az:mountain
berkeley:ca:pacific
los angeles:ca:pacific
denver:co:mountain
augusta:me:eastern
santa fe:nm:mountain
dallas:tx:central
houston:tx:central
seattle:wa:pacific

Sort by city
# sort -t":" sortme
augusta:me:eastern
berkeley:ca:pacific
dallas:tx:central
denver:co:mountain
houston:tx:central
los angeles:ca:pacific
phoenix:az:mountain
santa fe:nm:mountain
seattle:wa:pacific

# sort -t":" +1 +2 sortme
phoenix:az:mountain
berkeley:ca:pacific
los angeles:ca:pacific
denver:co:mountain
augusta:me:eastern
santa fe:nm:mountain
dallas:tx:central
houston:tx:central
seattle:wa:pacific

Delimited by a pipe, "|", symbol
# vi sortme
phoenix|az|mountain
los angeles|ca|pacific
augusta|me|eastern
houston|tx|central
dallas|tx|central
berkeley|ca|pacific
seattle|wa|pacific
denver|co|mountain
santa fe|nm|mountain

# sort -t"|" +1 sortme
phoenix|az|mountain
berkeley|ca|pacific
los angeles|ca|pacific
denver|co|mountain
augusta|me|eastern
santa fe|nm|mountain
dallas|tx|central
houston|tx|central
seattle|wa|pacific

No comments: