0

I have this file, that contains - among other quite random things - blocks like this:

# MODE:
bindsym $mod+z mode "$system_mode"
mode "$system_mode" {    
    bindsym Return mode "default"
    bindsym Escape mode "default"
}

foo

# MODE:
bindsym $mod+z mode "$other_mode"
mode "$other_mode" {    
    bindsym blah blah mode "default"
    bindsym foo bar "default"
}

bar

And I need to extract those to another file. I tried every option in the answers to this post but I got as far as extracting one block:

sed -e '1,/# MODE:/d' -e '/}/,$d' FILE  

returns

bindsym $mod+z mode "$other_mode"
mode "$other_mode" {    
    bindsym blah blah mode "default"
    bindsym foo bar "default"

And it is exactly what I need, but How can I get it to return all the blocks?

For some reason in the real file, the block returned is the first ; But with the above example, the block returned is the last one.

PS - I would prefer a "standard CLI tools" solution, but Perl or Python are acceptable, since they tend to be available anywhere nowadays.

yPhil
  • 8,049
  • 4
  • 57
  • 83
  • "For some reason in the real file, the block returned is the first ; But with the above example, the block returned is the last one. " I think for _that_ bit you might have a newline in the real file. To "fix", you can `sed -e '0,/# MODE:/d' -e '/}/,$d' FILE` i.e start from 0 – declension Oct 15 '22 at 14:27
  • What is the definition of your `blocks`? By which logic are the `blocks` distinguished from other `random things`? It would be better if you can include the random things in the example and illustrate your desired output. – tshiono Oct 15 '22 at 22:24
  • Each of those things are in the question : What a block of code *exactly* is, and there *are* "random things" in the example. Maybe read slower. – yPhil Oct 16 '22 at 15:56

1 Answers1

0

OK, I finally did it in Python:

#!/bin/env python3

import re
import os

f = open('FILE','r')
pattern = '# MODE:\n(.*?)\}'

content = f.read()

match = re.findall(pattern,content,re.MULTILINE|re.DOTALL)

for line in match:
    print(line)
yPhil
  • 8,049
  • 4
  • 57
  • 83