Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove block text between 2 patterns?

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 ?

like image 636
MOHAMED Avatar asked Jun 16 '26 17:06

MOHAMED


2 Answers

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?
    • 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
like image 71
Sundeep Avatar answered Jun 19 '26 06:06

Sundeep


With GNU awk for multi-char RS and RT:

$ awk -v RS='---END TEXT---\n' '{ORS=RT} NR==1' file
---BEGIN TEXT---
any text1
anytext2
anytext3
---END TEXT---

$ awk -v RS='---END TEXT---\n' '{ORS=RT} NR!=1' file
---BEGIN TEXT---
any text4
any text5
---END TEXT---

$ awk -v RS='---END TEXT---\n' '{ORS=RT} NR==2' file
---BEGIN TEXT---
any text4
any text5
---END TEXT---
like image 22
Ed Morton Avatar answered Jun 19 '26 08:06

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!