Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffle columns

Tags:

bash

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)

like image 767
tilefrae Avatar asked Nov 16 '14 09:11

tilefrae


2 Answers

Use awk.

awk '{print $2,$1,$3}' infile > outfile
like image 95
Avinash Raj Avatar answered Sep 28 '22 00:09

Avinash Raj


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.

like image 41
PM 2Ring Avatar answered Sep 28 '22 00:09

PM 2Ring