0

I want to convert multiple Columns to rows.

e.g

Input :

 A,0,10,12,14,16,2,
 B,10,10P

Output:

 A,0,0
 A,10,10
 A,12,12
 A,14,14
 A,16,16
 A,2,2
 B,10,10
 B,10P,10p

I tried but not sure how to repeat the certain columns.

awk '{FS=",";OFS="\n"}{print $1, $2, $3, $4, $5}' filename

2 Answers 2

3

This can be a way:

$ awk 'BEGIN{FS=OFS=","}{for (i=2;i<=NF; i++) print $1, $i, $i}' file
A,0,0
A,10,10
A,12,12
A,14,14
A,16,16
A,2,2
B,10,10
B,10P,10P

Explanation

  • BEGIN{FS=OFS=","} set input and output field separator as comma.
  • for (i=2;i<=NF; i++) print $1, $i, $i loop through all fields from 2nd, printing the first field plus the i-th twice.

Note that your attempt awk '{FS=",";OFS="\n"}{print $1, $2, $3, $4, $5}' filename was setting FS and OFS on every line, while it's better to do it once, in the BEGIN{} block.

Sign up to request clarification or add additional context in comments.

1 Comment

Setting FS as the OP did also wouldn't work for the first line, it's GOT to be done in BEGIN (or elsewhere before the first line of the file is read).
0

This might work for you (GNU sed):

sed -r 's/^([^,]+)(,[^,]+)/&\2\n\1/;//P;D' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.