Split a content in a file with specific interval base on the delimited values using UNIX command

Hi All,

we have a requirement to split a content in a text file every 5 rows and write in a new file .

conditions:

if 5th line falls between center of the statement . it should look upto after ";"

files are below format:

1	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
2	WHERE EMP='121'
3	;
4	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
5	WHERE EMP='121'
6	;
7	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
8	WHERE EMP='121'
9	;
10	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
11	WHERE EMP='121'
12	;
13	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
14	WHERE EMP='121'
15	;
16	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
17	WHERE EMP='121'

Output needed:

file 1:

1	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
2	WHERE EMP='121'
3	;
4	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
5	WHERE EMP='121'
6	;

file 2:

UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
8	WHERE EMP='121'
9	;
10	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
11	WHERE EMP='121'
12	;

file 3:

UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
14	WHERE EMP='121'
15	;
16	UPDATE TABLE TEST1 SET VALUE ='AFDASDFAS'
17	WHERE EMP='121'
18 :

Please dont print with line number, i make it as reference for your understanding.

Welcome KK230689,

I have a few to questions pose in response first:-

  • Is this homework/assignment? There are specific forums for these.
  • What have you tried so far?
  • What output/errors do you get?
  • What OS and version are you using?
  • What are your preferred tools? (C, shell, perl, awk, etc.)
  • What logical process have you considered? (to help steer us to follow what you are trying to achieve)
  • Is your requirement actually that you want three statements per file? I might suggest csplit for that.

Most importantly, What have you tried so far?

There are probably many ways to achieve most tasks, so giving us an idea of your style and thoughts will help us guide you to an answer most suitable to you so you can adjust it to suit your needs in future.

We're all here to learn and getting the relevant information will help us all.

Kind regards,
Robin

1 Like
rm -f outfile_*

file_count=1
line_count=1

outfile="outfile_$file_count"

while read line
do
   echo "$line" >> $outfile
   (( line_count = line_count + 1 ))
   [[ $line_count -ge 5 ]] && { echo "$line" | grep -q "^ *; *$" && {
         (( file_count = file_count + 1 ))
         (( line_count = 1 ))
      }
      outfile="outfile_$file_count"
   }
done < input_file
1 Like

This looks like it should work to me. Have you tested it? I don't think you need the echo "$line" | grep . If using ksh93 or bash 4 you could write:

[[ "${line}" =~ ";" ]] && [[ "${line_count}" -ge 5 ]] && {

Andrew

1 Like