easiest way to rearrange columns and manipulate text file
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 videos on Youtube
Jon Butler
Updated on September 18, 2022Comments
-
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
andsed
.-
Jeff Hewitt over 7 yearsHi. Welcome to U&L :).
awk
is probably the best tool for the job here. Check out its man page, accessed viaman awk
from your favorite terminal emulator. -
agc over 7 yearsPlease show what the output should look like.
-
-
Jon Butler over 7 yearsthank you! and especially for giving me an answer i can understand