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
somefield3:somefield2:somefield1
References:
http://unix.stackexchange.com/questions/35515/swap-two-columns-in-a-csv-using-sed
http://www.linuxquestions.org/questions/programming-9/remove-last-character-from-file-string-345339/
References:
http://unix.stackexchange.com/questions/35515/swap-two-columns-in-a-csv-using-sed
http://www.linuxquestions.org/questions/programming-9/remove-last-character-from-file-string-345339/