3

I have a file called test.txt that contains:

....Request....
asaksa
sda
dsad
dsad
....Request...
21mklk
nnm212
mkmr543
849238
....Request...
4392840
kndska
94i0-jkfjdk
smdla
.....Request..
839281
ksndlka
nsc
mcxmzl

I want all lines between two "Request" pattern should print to different -2 file like:

file1 :

asaksa
sda
dsad
dsad

file2:

21mklk
nnm212
mkmr543
849238

file3:

4392840
kndska
94i0-jkfjdk
smdla

file4:

839281
ksndlka
nsc
mcxmzl

like wise

2

How about just incrementing a file counter each time you encounter the Request string?

awk '/Request/ {n++; next}; {print > "file"n}' test.txt
1
csplit -f file -z --suppress-matched - '/Request/' '{*}' <<\DATA
....Request....
asaksa
sda
dsad
dsad
....Request...
21mklk
nnm212
mkmr543
849238
....Request...
4392840
kndska
94i0-jkfjdk
smdla
.....Request..
839281
ksndlka
nsc
mcxmzl
DATA

You're asking for how to use csplit, basically. Its job is to split its input file out into separate files based on context matches.

ls 

file00  file01  file02  file03

cat file00

asaksa
sda
dsad
dsad

cat file*

asaksa
sda
dsad
dsad
21mklk
nnm212
mkmr543
849238
4392840
kndska
94i0-jkfjdk
smdla
839281
ksndlka
nsc
mcxmzl
0

Or use the built-in variable NR for the record number:

awk -v RS='\\.+Request\\.+'  '{if (NR==1) next}  {print > "file"NR-1 }' test.txt

and doesn't create an empty file for file1.

This slightly longer one removes the empty line at the start and end of each output file:

awk -v RS='\\.+Request\\.+' -v ORS= '{if (NR==1) next}  { gsub("^\n",""); print > "file"NR-1 }' test.txt

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.