'save each grepped line as a separate .txt file using bash

I have a file .txt with some informations, i need to grep the "Report:" line and save each line in a different .txt file!

it should result something like this in the end:

case1.txt 
case2.txt 
case3.txt

I tried to

cat cases.txt| grep Report: | while read Report; do echo $Report | > /home/kali/Desktop/allcases/case.txt done

but it didnt work and just created one file called case.txt containing the last grepped "Report:"

I dont know if i was very clear then i'll show this screenshot:

cases

I wanted to split all theses reports in a different .txt file for each report!

These case informations are from a game, so dont worry!



Solution 1:[1]

awk would be better suited than grep and a while loop. If acceptable, you can try;

awk '/^Report/{cnt++;close(report); report="case"cnt".txt"}/./{print > report}' file.txt

Solution 2:[2]

perl -ne '++$i && `printf "$_" > case$i.txt` if /Report:/' cases.txt 

This is looping over cases.txt and shelling out printf "$_" > case$i.txt if the line matches /Report:/

Because it's perl there's some syntax and precedence tricks in here to make it terse and confusing.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HatLess
Solution 2 stevesliva