Home > Back-end >  save each grepped line as a separate .txt file using bash
save each grepped line as a separate .txt file using bash

Time:05-25

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!

CodePudding user response:

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

CodePudding user response:

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.

  • Related