chas
chas

Reputation: 1645

How to flip string using linux in specific columns

I have few columns as shown below:

col1 col2 col3 col4 a/t t/g g/t f/g
col3 col2 col4 col5 t/a g/t f/g g/t

I would need to flip the values in columns after 4, and the sample output is shown below:

col1 col2 col3 col4 t/a g/t t/g g/f
col3 col2 col4 col5 a/t t/g g/f t/g

I tried using the -rev option in bash but it prints the whole row in the inverted direction (mirror image). Is there an alternate solution for this just to flip the strings as shown in the output? Thanks in advance.

Upvotes: 0

Views: 106

Answers (2)

William Pursell
William Pursell

Reputation: 212288

perl -lane 'print join " ", @F[0..3], map { scalar reverse $_}  @F[4..$#F]'

Upvotes: 0

guido
guido

Reputation: 19194

You don't say what the first 4 column may contain, so I assume this would be enough

sed 's/\(\w\)\/\(\w\)/\2\/\1/g' <yourfile>

like:

$ cat test
col1 col2 col3 col4 t/a g/t t/g g/f
col3 col2 col4 col5 a/t t/g g/f t/g

$ sed 's/\(\w\)\/\(\w\)/\2\/\1/g' test
col1 col2 col3 col4 a/t t/g g/t f/g
col3 col2 col4 col5 t/a g/t f/g g/t

if you want to save the result to a file, redirect sed output:

$ sed 's/\(\w\)\/\(\w\)/\2\/\1/g' test > newfile

Upvotes: 1

Related Questions