Shell – Combining every two column values in file

awkcolumnssedshell

I have a file with (with only one line) with multiple columns say 4 (in this case) :

A B C D

And I want the output as every possible combination of column values taking 2 at a time like:

AB 
AC
AD
BC
BD
CD

where AB and BA are equivalent. I have tried the code: sed 's! \([^ ]\+\)\( \|$\)!\1 !g' <file_name> but it gives the output as AB CD.

Please suggest how to do this using awk or any shell command.

Best Answer

With awk:

awk '{for(i=1;i<=NF;i++){for(j=i+1;j<=NF;j++){print $i$j;}}}' file

It's two nested for loops:

  • for(i=1;i<=NF;i++) loop trough all fields
    • for(j=i+1;j<=NF;j++) then for each field, loop trough all remaining fields (start at i+1)
    • print $i$j print both field values.

The output:

AB
AC
AD
BC
BD
CD
Related Question