Shell – easiest way to rearrange columns and manipulate text file

shell-scripttext processing

Learning linux in school and working on manipulating text files at the moment. Looking to learn a few shortcuts here and there along the way.
Currently I have a text file with content such as:

First    Last   111 E. Road    New York    NY
First2   Last2  222 w. Road    Newark      NJ

We're supposed to write a script to rearrange the columns and comma delimit instead of tab delimit. What i did was simply cut each field and put into its own tmpfile and then pasted together as such:

paste tmplast tmpfirst tmpstate tmpaddress | tr '\t' ',' > finished

Is there a faster way rather than cutting everything into a tmp file and pasting together? I'm very new to linux and the only commands I've learned for manipulating files are like tr and sed.

Best Answer

You can do it in awk like this:

awk 'BEGIN {FS="\t"; OFS=","} {print $2, $1, $5, $3, $4}' file

FS and OFS specify the "(input) field separator" and "output field separator", and then the order in which to print fields can be specified explicitly using the $ notation. (No temporary files needed.)

Output:

Last,First,NY,111 E. Road,New York
Last2,First2,NJ,222 w. Road,Newark
Related Question