user247430
user247430

Reputation: 3

How to get the contents specified in the brackets?

I want to extract the content written in a file. Let us take an example

{{{
      How 
      R 
      U
}}}

{{{ Hi }}}

I want to print the output like this

 How
 R
 U

 Hi

Upvotes: 0

Views: 56

Answers (3)

ctac_
ctac_

Reputation: 2471

With sed

sed '/{{{/!d;:A;/\}\}\}/!{N;bA};s/{{{//;s/}}}//;s/ *//g' infile

Or

sed -E '/\{{3}/!d;:A;/\}{3}/!{N;bA};s/\{{3}| *|\}{3}//g' infile

Upvotes: 0

nbari
nbari

Reputation: 26905

By using regular expressions this becomes tricky, mainly because grep or awk seem not to support the lookahead.

To extract or match only the text within the curly braces this regex could be used: https://regex101.com/r/ASFIFa/1

[^{\}]+(?=})

Therefore you could give a try to the ag - The Silver Searcher, something like this produce your required output:

$ ag -o '[^{\}]+(?=})' input.txt 

To remove the leading spaces:

$ ag -o '[^{\}]+(?=})' input.txt | sed 's/^ *//'

Upvotes: 0

P....
P....

Reputation: 18351

Well, this is not regex this is using gawk multi-character RS.

awk -v RS='}}}|{{{' 'NF' inputfile

      How
      R
      U

 Hi

You can pipe above command with something like this sed -r 's/^ +//g' to remove extra spaces at the start of the line.

Upvotes: 2

Related Questions