1

I have a file with names. Each line represents a connection between the persons. But there also might be only one name in a line, too.

Donald Duck;Daisy Duck;Della Duck;
Fethry Duck;Dudly D. Duck;Donald Duck;
Della Duck;Dudly D. Duck;Moby Duck;
Dugan Duck;Donald Duck;Dimwitty Duck;Whitewater Duck;
Lonesome Duck;

I would like to permutate through the lines. To result should be like

Donald Duck;Daisy Duck
Donald Duck;Della Duck
Daisy Duck;Della Duck
Fethry Duck;Dudly D. Duck
Fethry Duck;Donald Duck
Dudly D. Duck;Donald Duck
Della Duck;Dudly D. Duck
Della Duck;Moby Duck
Dudly D. Duck;Moby Duck
Dugan Duck;Donald Duck
Dugan Duck;Dimwitty Duck
Dugan Duck;Whitewater Duck
Donald Duck;Dimwitty Duck
Donald Duck;Whitewater Duck
Dimwitty Duck;Whitewater Duck
Lonesome Duck;

The solution provided on Generating permutations using bash does not consider words but single characters.

lukascbossert
  • 375
  • 1
  • 11

1 Answers1

2

It seems you want 2-combinations of names in each line. A bash script for this could be something like that:

#!/bin/bash

while IFS=\; read -r -a names; do
    if ((${#names[@]} == 1)); then # if we have only one name, just echo it
        echo "${names[0]}"
    else
        for ((i = 0; i < ${#names[@]} - 1; ++i)); do
            for ((j = i + 1; j < ${#names[@]}; ++j)); do
                echo "${names[i]};${names[j]}"
            done
        done
    fi
done < names.txt
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • great! I am sorry, I forgot to write that there is also the possibility that there is only one name in a line `Duck;`. That should still be printed as it is (updated my question). – lukascbossert Jul 10 '20 at 14:49
  • 1
    This is my answer exactly! You got here first. +1 – glenn jackman Jul 10 '20 at 14:55
  • 1
    I'd suggest the condition for the `i` loop could be `i < ${#names[@]} - 1` -- as it currently stands, the `j` loop has zero iterations when `i` is the last index. – glenn jackman Jul 10 '20 at 14:57
  • @glennjackman It is a *micro optimization*, but your suggestion is fine and I complied with it. – M. Nejat Aydin Jul 10 '20 at 15:03