Shuffle columns

What is the best way to reorder columns in bash ?

Real example:

I have an ONE.txt file that contains:

 firstName secondName telNumber 

I want to create a SECOND.txt file from the first file

 secondName firstName telNubmer 

How can i do this? (Only substitution of columns in one row)

+5
source share
2 answers

Use awk.

 awk '{print $2,$1,$3}' infile > outfile 
+8
source

And just for fun, here's a sed solution that is (almost) equivalent in action to the Avinash Raj awk team.

 sed 's/[[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)[[:space:]]*/\2 \1 /' infile > outfile 

Obviously, the awk solution is much easier to read. :) OTOH, the sed version handles strings with more than three fields.

And if we can guarantee that the strings will always be exactly the form

 firstName secondName telNumber 

without extra spaces or spaces (e.g. tabs), we can condensate the sed command to:

 sed 's/\([^ ]*\) \([^ ]*\)/\2 \1/' 

I just did a quick time test in a file containing 500,000 lines (generated using awk). The condensed sed version is 10 times slower than the awk version. I assumed this would be a bit slower as sed uses regular expressions, but I did not think it would be much slower.

FWIW, the Python equivalent of the Avinash Raj awk command, is about two times slower than the awk version.


I'm just re-reading the question. It looks like the file in the OP has only one row of data. In this case, we can do this very simply using pure bash:

 read abc < ONE.txt;echo > SECOND.txt "$b $a $c" 

Or maybe tilefrae says they want the swap to happen on the first line, and to make a plain copy of the following lines ... If so, it is easy to change either awk or sed programs to do this,

+2
source

Source: https://habr.com/ru/post/1206972/


All Articles