user10657934
user10657934

Reputation: 157

Applying some changes in a tab separated text file using AWK

I have a tab separated text file like this small example:

small example:

#type   cNA NA  me  ion Dir Mism    Bulge
X   GAAGC   GAAGa   chr8    3997355     -   5   0
X   GAAGC   GAAGC   chr8    11720692    +   5   0
X   GAAGC   GAAGC   chr8    23414961    -   5   0

and would like to make a new file like this expected output in which the 1st line is removed and columns are re-organised in this order:

1) columns 1 and 8 are removed.
2) 2nd column (small example file) moved to 1st column (expected output).
3) 4th column moved to the 2nd column.
4) 5th column moved to 3rd column.
5) 3rd column moved to 4th column.
6) 6th column moved to 5th column.
7) 7th column moved to 6th column.

here is the expected output:

expected output:

GAAGC   chr8    3997355     GAAGa   -   5
GAAGC   chr8    11720692    GAAGC   +   5
GAAGC   chr8    23414961    GAAGC   -   5

I am trying to do that in AWK using the following command:

awk -F '\t' '{ print $2 $4 $5 $3 $6 $7}' infile.txt > output.txt

but the results I am getting is not like expected output. do you know how to fix the code?

Upvotes: 0

Views: 43

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133780

I am not sure why you are re-assigning the fields? When we can simply print them like:

awk 'FNR==1{next} {print $2,$4,$5,$3,$6,$7}' Input_file

OR to add a tab separated output use:

awk 'BEGIN{OFS="\t"} FNR==1{next} {print $2,$4,$5,$3,$6,$7}' Input_file

OR

awk 'FNR>1{print $2,$4,$5,$3,$6,$7}' Input_file

or

awk 'BEGIN{OFS="\t"} FNR>1{print $2,$4,$5,$3,$6,$7}' Input_file


In case OP willing to use field re-assignment approach only then one could try following.

awk '
BEGIN{
  OFS="\t"
}
FNR==1{
  next
}
{
  $1=$2
  $2=$4
  $4=$3
  $3=$5
  $5=$6
  $6=$7
  $7=$8=""
  sub(/ +$/,"")
}
1
'  Input_file

Upvotes: 2

Related Questions