Skip to main content
2 of 5
added 300 characters in body
Ed Morton
  • 35.9k
  • 6
  • 25
  • 60

Using any awk, in case that's OK instead of sed:

$ awk 'NR==FNR{map[$2]=$1; next} FNR>1{$1=map[$1]; $2=map[$2]} 1' file2 file1
a   b   nSites  J9
SF10 SF11 3092845 1
SF10 SF12 3139733 1
SF10 SF13 3339810 1
SF10 SF14 3124263 1

To get the output to look tabular there's various approaches including just piping to column -t:

$ awk 'NR==FNR{map[$2]=$1; next} FNR>1{$1=map[$1]; $2=map[$2]} 1' file2 file1 | column -t
a     b     nSites   J9
SF10  SF11  3092845  1
SF10  SF12  3139733  1
SF10  SF13  3339810  1
SF10  SF14  3124263  1

or making the output tab-separated instead of blank-separated:

$ awk -v OFS='\t' 'NR==FNR{map[$2]=$1; next} FNR>1{$1=map[$1]; $2=map[$2]} {$1=$1} 1' file2 file1
a       b       nSites  J9
SF10    SF11    3092845 1
SF10    SF12    3139733 1
SF10    SF13    3339810 1
SF10    SF14    3124263 1

or using printf:

$ awk 'NR==FNR{map[$2]=$1; next} FNR>1{$1=map[$1]; $2=map[$2]} {printf "%-10s %-10s %-10s %-10s\n", $1, $2, $3, $4}' file2 file1
a          b          nSites     J9
SF10       SF11       3092845    1
SF10       SF12       3139733    1
SF10       SF13       3339810    1
SF10       SF14       3124263    1

The above was run on these input files:

$ head file{1,2}
==> file1 <==
a   b   nSites  J9
0   1   3092845 1
0   2   3139733 1
0   3   3339810 1
0   4   3124263 1

==> file2 <==
SF10    0
SF11    1
SF12    2
SF13    3
SF14    4
Ed Morton
  • 35.9k
  • 6
  • 25
  • 60