1

I have a file (comma separated) on a Linux system with 3 columns. I want to start new column after every 4th row.

Input:

col1,col2,col3 
1,disease1,high
1,disease2,low 
1,disease3,high
col1,col2,col3 
2,disease1,low 
2,disease2,low 
2,disease3,high
col1,col2,col3
3,disease1,low
3,disease2,low
3,disease3,low

Expected output:

col1,col2,col3,col1,col2,col3,col1,col2,col3
1,disease1,high,2,disease1,low,3,disease1,low
1,disease2,low,2,disease2,low,3,disease2,low
1,disease3,high,2,disease3,high,disease3,low

i.e. I want exactly 4 lines of output, each line is the result of joining every fourth line of the input with a comma.

2

With awk:

awk '{a[NR%4] = a[NR%4] (NR<=4 ? "" : ",") $0}
     END{for (i = 1; i <= 4; i++) print a[i%4]}' < input.txt
0

Try pasteing four lines into one, reading those into four variables, appending each to output lines:

paste -s -d"   \n" file | 
{ while read A B C D 
    do  L1="$L1$DL$A"
        L2="$L2$DL$B"
        L3="$L3$DL$C"
        L4="$L4$DL$D"
        DL=, 
    done 
  printf "%s\n" "$L1" "$L2" "$L3" "$L4"  
}
col1,col2,col3,col1,col2,col3,
1,disease1,high,2,disease1,low,
1,disease2,low,2,disease2,low,
1,disease3,high,2,disease3,high,

EDIT: or, a bit simpler, no paste needed:

while read A && read B && read C && read D     
  do    L1="$L1$DL$A"
        L2="$L2$DL$B"
        L3="$L3$DL$C"
        L4="$L4$DL$D"
        DL=,     
  done < file 
printf "%s\n" "$L1" "$L2" "$L3" "$L4"

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.