0

I have a list in the following format:

group1;visitor1,visitor2,visitor3,
group2;visitor4,visitor5

From the list above, I need to generate a list in the following way:

group1,visitor1
group1,visitor2
group1,visitor3
group2,visitor4
group2,visitor5
2
  • 2
    Did you make some efforts towards solving this problem?
    – Inian
    Jun 10, 2019 at 11:02
  • 1
    Is trailing comma in first line intended?
    – Cyrus
    Jun 10, 2019 at 11:14

2 Answers 2

0

This is very similar to Using AWK for an array and a few other questions. The main idea is to print each field from field two onwards on a separate line prepended by the first field.

In this case, we specify that the field separator is either , or ;, and we also make sure not to print empty fields (there's an empty field at the end of the first line in the given data). The OFS variable that we set on the command line with -v is the output separator string that will be used to delimit the output fields, and NF is the number of fields on the line.

awk -F '[,;]' -v OFS=',' '{ for (i = 2; i <= NF; ++i) if ($i != "") print $1, $i }' file

Given the data in the question, this generates

group1,visitor1
group1,visitor2
group1,visitor3
group2,visitor4
group2,visitor5
0

This can be done using GNU sed like so:

sed -r 's:,$::;y:;,:,;:;:l;s:^(([^,]+)[^;]+);:\1\n\2,:;tl' file

For each input line I'm deleting the trailing comma, if any, then I'm switching commas with semicolons to help with printing. After that, I'm running a search and replace loop, between :l and tl to prepend the group name to each visitor on the current input line.

1
  • Those advanced in sed will realize that if there is only 1 visitor plus a trailing comma, two (unsuccessful) s iterations are done instead of one. This is because I've used another s command at the beginning to delete the trailing comma, so t will branch regardless. I could add another label and t at the beginning, but it works without :)
    – seshoumara
    Jun 10, 2019 at 16:23

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.