Script to duplicate lines

Hello,

I'm trying to write an script that in a txt with lines with 2 or more columns separated by commas, like

hello, one, two
bye, goal
first, second, third, fourth
hard, difficult.strong, word.line

will create another in which if a line has more than 2 columns, it will have another line and with only the 1st and 2nd column, another line with 1st and 3rd column, etc . Like this:

hello, one
hello, two
bye, goal
first, second
first, third
first, fourth
hard, difficult.strong
hard, word.line

Any help or tip?

Thank you very much:)

$ nawk -F, '{if(NF>2){printf("%s,%s\n",$1,$2);for(i=3;i<=NF;i++){printf("%s,%s\n",$1,$i)}}else{print}}' input.txt
hello, one
hello, two
bye, goal
first, second
first, third
first, fourth
1 Like

Thank you, it worked :slight_smile:

you can use awk,nawk or gawk:-


gawk '{for(i=2;i<=NF;i++){print $1,$i}}' FS="," OFS="," infile.txt > outfile.txt

BR
:D:D:D

1 Like
# awk -F"," '{for(i=2;i<=NF;i++)print $1FS$i}' infile
hello, one
hello, two
bye, goal
first, second
first, third
first, fourth
hard, difficult.strong
hard, word.line
1 Like