user2894829
user2894829

Reputation: 815

BASH Convert columns to rows with labels

I am trying to process a file content using bash.

Assume the content is made up by labels and elements, such as:

A 1,2,3,4
B 5

Now it needs to be converted to:

A 1
A 2
A 3
A 4
B 5

I tried sed to insert newline every n characters but I cannot insert labels to new lines and it is not seperated as expected.

sed -e "s/.\{3\}/&\n/g" < test.txt

result:

A 1
,2,
3,4

B 8

Any help is appreciated...

Upvotes: 0

Views: 62

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

try this

awk -F "[ ,]" '{for(i=2;i<=NF;i++)print $1, $i}' i.txt

Output:

A 1
A 2
A 3
A 4
B 5

Upvotes: 1

Related Questions