1

Considering following comma delimited input file:

1,13/06/17,01,03,D151
2,25/06/17,04,06,D154

Using 3rd and 4th fields from each record, I need to generate serial numbers with same other fields of the record that SN belong to.

for first record (03 - 01 = 2+1) This number of new records

for 2nd record (06 - 04 = 2+1) This number of new records

Output:

1,13/06/17,01,03,D151
1,13/06/17,01,03,D151,1
1,13/06/17,01,03,D151,2
1,13/06/17,01,03,D151,3
2,25/06/17,04,06,D154
2,25/06/17,04,06,D154,4
2,25/06/17,04,06,D154,5
2,25/06/17,04,06,D154,6

Simply using for I can generate the SNs yet linking them to the original record is the issue here.

2 Answers 2

4

Something like:

awk -F, '{print; for (i = 0+$3; i <= $4; i++) print $0 FS i}'
2
  • Thanks, For why the zero in i = 0+$3 ?
    – Eng7
    Jul 4, 2017 at 13:36
  • @Eng7, that's to convert the 03 to 3. 0+$3 converts it to a number, and it's converted back to a string (but this time using the canonical integer representation) when printed. Jul 4, 2017 at 16:28
1
while IFS= read -r l; do
   printf '%s\n' "$l" | tee log
   for i in $(seq $(cut -d, -f3,4 log | tr , '\n')); do
     printf '%s,%s\n' "$l" "$i"
   done
done < input.csv

perl -F, -pe 's|(.*)\K|join $/, $,, map "$1,$_", 0+$F[2]..$F[3]|ex'  input.csv

output:

1,13/06/17,01,03,D151
1,13/06/17,01,03,D151,1
1,13/06/17,01,03,D151,2
1,13/06/17,01,03,D151,3
2,25/06/17,04,06,D154
2,25/06/17,04,06,D154,4
2,25/06/17,04,06,D154,5
2,25/06/17,04,06,D154,6

Explanation

  1. Current line saved into $1. The \n in the current record will not be saved into $1 as the . does not match a newline, unless the /s modifier is in effect.
  2. $F[2]..$F[3] => generate a sequence of numbers starting from left ending with right, in steps of 1. The 0+ artifact is there to take away the leading zeros that otherwise would result.
  3. map will perform the appropriate operation by combining the current line and the integer separated by a comma.
  4. All these strings generated in Step-3 are joined together by the $/ which is the RS and defaults to a newline.
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .