easiest way to rearrange columns and manipulate text file

18,529

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
Share:
18,529

Related videos on Youtube

Jon Butler
Author by

Jon Butler

Updated on September 18, 2022

Comments

  • Jon Butler
    Jon Butler almost 2 years

    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.

    • Jeff Hewitt
      Jeff Hewitt over 7 years
      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.
    • agc
      agc over 7 years
      Please show what the output should look like.
  • Jon Butler
    Jon Butler over 7 years
    thank you! and especially for giving me an answer i can understand