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

I see in the edit history of the question that in a previous incarnation of the question the OP showed sample input as screenshots of what appears to be Excel spreadsheets and someone else actually replaced those with the current space-separated textual input example. Given that, I'm going to assume the input will actually be comma-separated since that's the most common Excel export/import format in which case it'd look like:

$ 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

With the above input, using any awk:

$ awk 'BEGIN{FS=OFS=","} 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

If the input truly is space-separated (tabs and/or blanks), though, then still using any awk:

$ 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
Ed Morton
  • 35.9k
  • 6
  • 25
  • 60