What is the best way to reorder columns in bash
?
Real example:
I have file ONE.txt contains:
firstName secondName telNumber
I want to create file SECOND.txt from the first file
secondName firstName telNubmer
How can I accomplish this? (Only swapping columns one row)
Use awk.
awk '{print $2,$1,$3}' infile > outfile
And just for fun, here's a sed solution that's (almost) equivalent in action to Avinash Raj's awk command.
sed 's/[[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)[[:space:]]*/\2 \1 /' infile > outfile
Obviously, the awk solution is much easier to read. :) OTOH, the sed version copes with lines with more than 3 fields.
And if we can guarantee that the lines will always be exactly of the form
firstName secondName telNumber
with no extra spaces or other whitespace (eg tabs), we can condense the sed command down to:
sed 's/\([^ ]*\) \([^ ]*\)/\2 \1/'
I just did a quick timing test on a file containing 500,000 lines (generated using awk). The condensed sed version is 10 times slower than the awk version. I guessed it would be a bit slower, since sed is using regexes, but I didn't think it'd be that much slower.
FWIW, a Python equivalent of Avinash Raj's awk command is about twice as slow as the awk version.
I just re-read the question. It appears that the file in the OP only has one row of data. In that case, we can do this very simply, using pure bash:
read a b c < ONE.txt;echo > SECOND.txt "$b $a $c"
Or maybe tilefrae is saying that they only want the swap to happen on the first row, and to make a plain copy of subsequent rows... If so, it's easy to modify either the awk or sed programs to do just that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With