#!/usr/bin/perl use strict; use warnings; my $data = ; chomp $data; while () { my ($rpos, $lpos) = (0, 0); $rpos = index($data, "}", $rpos); last if $rpos < 0; $lpos = rindex($data, "{", $rpos); last if $lpos < 0; # $lpos + 1 so we don't extract the the { # -1 at the end to exclude the } my $extract = substr($data, $lpos + 1, $rpos - $lpos - 1); # get rid of these braces. substr($data, $lpos, 1) = "<"; substr($data, $rpos, 1) = ">"; # if you wanted to replace the entire section including braces # substr($data, $lpos, $rpos - $lpos + 1) = "<>"; print "|${extract}|\n"; } print "|${data}|\n"; __DATA__ text text {scope 4 text {scope 2 text {scope 1 text} scope 2 text} scope 4 text {scope 3 text} scope 4 text } text text #### |scope 1 text| |scope 2 text scope 2 text| |scope 3 text| |scope 4 text scope 2 text> scope 4 text scope 4 text | |text text scope 2 text> scope 4 text scope 4 text > text text|