I'm trying to write a function which reads text from a large file and writes specific blocks of text to another file. 

Example file 

```
@Tag
Scenario 1:
   Do thing 1
   Do thing 2
Scenario 2:
   Do thing 1
   Do thing 3
@Tag2
Scenario 3:
   Do thing 1
   Don't do thing 4

```

I'm trying to read through this file line by line (using IFS right now) and want the output to be something like this: 

File 1

```
@Tag
Scenario 1:
   Do thing 1
   Do thing 2

```

File 2

```
Scenario 2:
   Do thing 1
   Do thing 3

```

File 3

```
@Tag2
Scenario 3:
   Do thing 1
   Don't do thing 4

```

I have the pieces in place to read through the file and separate out on the "Scenario" pattern and the lines after it, but the problem I'm running into is trying to figure out how to capture the @Tag pattern and write it if it exists above the "Scenario" pattern. 

Edit: here is the current relevant part of the script: 

```
function writeToTestFile {
while IFS='' read -r line || [[ -n "$line" ]]; do
    #if line matches the tag pattern of "@" followed by anything, store it
    if [[ $line == *@* || "" ]]; then
        local tagValue=$line

    #if line in file matches "Scenario:" pattern, write to new file
    elif [[ $line == *Scenario:* ]]; then
        fileToWriteTo=$filename$counter$extention
        ((counter++))
        echo "writing to $fileToWriteTo"
        touch $dirToWriteTo/$fileToWriteTo

    else
        #if line does not match "Scenario:" pattern, check for existing file and write to that
        if [[ -e $dirToWriteTo/$fileToWriteTo ]]; then
            echo "   "$line >> $dirToWriteTo/$fileToWriteTo
        fi
    # if file does not exist and line does match pattern, do nothing
    fi

done < "$1"

```

}