5

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.

2
  • 1
    Hi. Welcome to U&L :). awk is probably the best tool for the job here. Check out its man page, accessed via man awk from your favorite terminal emulator.
    – Joseph R.
    Feb 13 '17 at 5:02
  • 1
    Please show what the output should look like.
    – agc
    Feb 13 '17 at 7:28
8

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
1
  • 1
    thank you! and especially for giving me an answer i can understand
    – Jon Butler
    Feb 14 '17 at 4:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.