3

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.

  • Have you tried anything so far? How did it fail? Do you only have one line in your input file? Is AB the same as BA? Please edit and clarify. – terdon Apr 8 '16 at 8:41
  • its like C (4,2) : taking 2 at a time out of total of 4 values. Combination of every possible 2 values with AB and BA being same result – Anshul Arora Apr 8 '16 at 8:41
  • I have tried this : sed 's! ([^ ]\+)( \|$)!\1 !g' <file> ,, but it gives output as AB CD. – Anshul Arora Apr 8 '16 at 8:43
4

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.