Question: I have the following text in my file

```
---BEGIN TEXT---
any text1
anytext2
anytext3
---END TEXT---
---BEGIN TEXT---
any text4
any text5
---END TEXT---

```

I want to remove the **2nd** text block from `"---BEGIN TEXT---"` to `"---END TEXT---"`

How I can make that with a linux command

So my file will contains only:

```
---BEGIN TEXT---
any text1
anytext2
anytext3
---END TEXT---

```

I know how to remove the 1st block with the following command:

```
sed -n '/BEGIN TEXT/,/END TEXT/{p;/PAT2/q}' file.txt

```

How I can modify my `sed` comand to remove the 2nd part and not the first part? or use another command like `awk` ?

Answer: 
Here's a modified sample for a generic solution

```
$ cat ip.txt 
foobaz
---BEGIN TEXT---
block 1
any text
---END TEXT---
1234567
---BEGIN TEXT---
block 2
any text
---END TEXT---
helloworld
---BEGIN TEXT---
block 3
any text
---END TEXT---
42424242

```

To remove only the second block:

```
$ awk -v b=2 '/BEGIN TEXT/{f=1; c++} !(f && c==b); /END TEXT/{f=0}' ip.txt 
foobaz
---BEGIN TEXT---
block 1
any text
---END TEXT---
1234567
helloworld
---BEGIN TEXT---
block 3
any text
---END TEXT---
42424242

```

* `-v b=2` the block to be removed
* `/BEGIN TEXT/{f=1; c++}` set flag and increment counter when starting regex is matched
* `/END TEXT/{f=0}` clear flag for ending regex
* `!(f && c==b)` don't print input record if flag is set and it is the block specified by `b` variable

Further reading:

* [How to select lines between two patterns?](https://stackoverflow.com/questions/38972736/how-to-select-lines-between-two-patterns)
	+ the solution here is a variation on `awk '/PAT1/{flag=1} flag; /PAT2/{flag=0}'` which is explained in the linked Q&A
* [my tutorial on dealing with specific blocks](https://github.com/learnbyexample/Command-line-text-processing/blob/master/gnu_awk.md#specific-blocks)
simplistically, `sed -i '/---END TEXT---/q;' txtfile` though I don't think that's actually the answer you wanted. 

You *could* write a more complex sed script that does a lot of hold and pattern space manipulation, but meh. 

If what you specifically wanted was to exclude the second set, here's a way using just bash. Not better than the awk answers, but I like to contribute variety.

```
c=0; while read line; do [[ "$line" = "---BEGIN TEXT---" ]] && (( c++ )); (( c != 2 )) && echo "$line"; done <txt

```

or, formatted -

```
c=0
while read line
do [[ "$line" = "---BEGIN TEXT---" ]] && (( c++ ))
   (( c != 2 )) && echo "$line"
done < txtfile

```