Skip to content
Advertisement

extract multiple blocks of text to a new file

I need help extracting blocks of information from a single text file into new files or some form where I can manipulate the data from each block.

Example:

[Block1]
this=that
here=there
why=why_not

[Block2]
this=those
here=there
why=because

I need to be able to display and/or manipulate the variables (which I can do if I can isolate the right one). I don’t mind writing each one of these blocks to a temp file

So, how would I change here=there to here=anywhere only in Block2?

I’ve tried to figure this out using sed/awk but no avail.

Advertisement

Answer

Possible solution using Perl:

perl -00 -pe '/^[Block2]n/ or next; s/^here=there$/here=anywhere/m'

-p tells perl to wrap the code in an implicit input/output loop (similar to sed).

-00 tells perl to process the input in units of paragraphs (instead of lines).

-e ... specifies the program. We first make sure the paragraph starts with [Block2] (otherwise we skip all other processing). Then we replace a line of the form here=there with here=anywhere.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement