Saturday, March 2, 2013

Unix swap fields separated by :

Unix homework 1

Requirement: Using sed(Stream editor) write a command which swaps the first and third field in a given file. The fields in the file are separated by colon (:)

Solution: sed 's/^\([^:]*:\)\([^:]*:\)\([^:]*\)/\3:\2\1/;s/:$//' -i your_filename


Explanations:

'^' start at the beginning of the line
\( \) a grouping 
[^:] any character except ':' 
* zero or more times 
: the character ':'
;s/:$// in here ; is used to separate commands, s/:$// is used to remove last :
-i is used to directly edit the file, if you remove -i then the result will be displayed on the screen instead of editing the file

Example of file content:
field1:field2:field3
somefield1:somefield2:somefield3

After running the command:
field3:field2:field1