neversaint
neversaint

Reputation: 63984

Re-ordering columns with a Perl one-liner

How do you reorganize this with one liner

foo  r1.1   abc
foo  r10.1  pqr
qux  r2.1   lmn
bar  r33.1  xpq

# In fact there could be more fields that preceeds column with "rxx.x".

Into this

r1.1  foo  abc
r10.1 foo  pqr
r2.1  qux  lmn
r33.1 bar  xpq

Basically, put second column into the first and everything else that succeeds it, after.

Upvotes: 2

Views: 1123

Answers (6)

Mushal
Mushal

Reputation: 97

file
a 5 ss
b 3 ff
c 2 zz

cat file | awk '{print $2, $1, $3}' # will print column 2,1,3

5 a ss
3 b ff
2 c zz

#or if you want to sort by column and print to new_file

cat file | sort -n -k2 | awk '{print $0}' > new_file

new_file
c 2 zz
b 3 ff
a 5 ss

Upvotes: 1

TLP
TLP

Reputation: 67900

The basic answers are provided by others, I considered the case of fixed width data with possible empty fields:

>cat spacedata.txt
foo  r1.1   abc
foo  r10.1  pqr
qux  r2.1   lmn
bar  r33.1  xpq
     r1.2   cake
is   r1.2   alie

>perl -lpwE '$_=pack "A7A5A*", (unpack "A5A7A*")[1,0,2];' spacedata.txt
r1.1   foo  abc
r10.1  foo  pqr
r2.1   qux  lmn
r33.1  bar  xpq
r1.2        cake
r1.2   is   alie

Upvotes: 2

Birei
Birei

Reputation: 36252

Content of 'infile':

foo  r1.1   abc
foo  r10.1  pqr
qux  r2.1   lmn
bar  r33.1  xpq

Perl one-line:

perl -pe 's/\A(\S+\s+)(\S+\s+)/$2$1/' infile

Result:

r1.1   foo  abc
r10.1  foo  pqr
r2.1   qux  lmn
r33.1  bar  xpq

Upvotes: 2

Zaid
Zaid

Reputation: 37136

$ perl -pale '$_ = "@F[1,0,2..$#F]"' file

If it's tab-separated, a little more is needed:

$ perl -pale 'BEGIN { $"="\t"; } $_ = "@F[1,0,2..$#F]"' file

Upvotes: 3

JRFerguson
JRFerguson

Reputation: 7516

If you have more than three columns, you will want something like:

perl -lane 'print join q( ),$F[1],$F[0],@F[2..@F-1]'

Upvotes: 3

ennuikiller
ennuikiller

Reputation: 46965

Assuming your text is in the file "test", this will do it:

perl  -lane 'print "$F[1] $F[0] $F[2]"' test

Upvotes: 4

Related Questions