Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split rows to multiple line based on comma : one liner solution

Tags:

sed

awk

I want to split the following format to unique lines

Input:

17:79412041:C:T,CGGATGTCAT
17:79412059:C:G,T
17:79412138:G:A,C
17:79412192:C:G,T,A

Desired output

17:79412041:C:T
17:79412041:C:CGGATGTCAT
17:79412059:C:G
17:79412059:C:T
17:79412138:G:A
17:79412138:G:C
17:79412192:C:G
17:79412192:C:T
17:79412192:C:A

Basically split the input to unique rows or firstID:secondID:thirdID:FourthID. Here multiple row may have firstID:secondID:thirdID may be common and the FourthID is the one it make each raw unique(that was seperated by "," in the input).

Thanks in advance Shams

like image 863
shams Avatar asked Aug 30 '26 07:08

shams


2 Answers

awk one-liner

$ awk -F":" '{gsub(/,/,":"); a=$1FS$2FS$3; for(i=4; i<=NF; i++) print a FS $i;}' f1
17:79412041:C:T
17:79412041:C:CGGATGTCAT
17:79412059:C:G
17:79412059:C:T
17:79412138:G:A
17:79412138:G:C
17:79412192:C:G
17:79412192:C:T
17:79412192:C:A

We are first replacing all , with : to keep a common delimiter i.e. :

We are then traversing from 4th field to end and printing each field by prefixing first three fields.

like image 76
Rahul Verma Avatar answered Sep 01 '26 09:09

Rahul Verma


This one-liner here:

$ awk -F':' '{ split($4,a,","); for (i in a) { print $1":"$2":"$3":"a[i] } }' data.txt

Produces:

17:79412041:C:T
17:79412041:C:CGGATGTCAT
17:79412059:C:G
17:79412059:C:T
17:79412138:G:A
17:79412138:G:C
17:79412192:C:G
17:79412192:C:T
17:79412192:C:A

Explanation:

split(string, array, delimiter)

splits the string by the delimiter, and saves the pieces into the array.

The for-in loop simply prints every piece in the array with the first three entries.

The -F':' part defines the top-level delimiter.

like image 41
Andrey Tyukin Avatar answered Sep 01 '26 11:09

Andrey Tyukin