art vanderlay
art vanderlay

Reputation: 2463

use sed to remove first Nth and last Nth characters from string only if matching X

I would like to use sed to remove the first Nth occurrences and the last Nth occurrences of a specific symbol in each string. For example, I would like to remove the first and last square brackets from the string below. The number of nested brackets is unknown, it could be

[{string[substring]string}]

or

[[[{string[substring]string}]]]

after sed should leave

{string[substring]string}

I tried following the logic of replace up to nth match and How to remove the last character from all lines but only if it is a certain character but could not find a formula that worked for an unknow amount of nested brackets.

Worst case I could recursively test the string to get the number of nested brackets, then remove that number of characters. Would that be a better method and what would the formula look like? I tried sed -r 's/.{2}//' -e 's/ .{2}$//' with no luck

Thx Art

Upvotes: 1

Views: 533

Answers (1)

midori
midori

Reputation: 4837

You don't have to count brackets, you just need to use proper pattern. You can do it like this:

sed "s/^\[*{/{/;s/}\]*$/}/"

there are two patterns here for replace, s means replace what is before / to what is after:

s/^\[*{/{/

This one will seek for { with any amount of [ starting from the beginning of the string. ^ - means beginning of the string, * means anything, using \ we escaping [. So we replacing here ^\[*{ with just {.

s/}\]*$/}/

Vise versa situation is here, but we seek for } with any amount of ] till the end of the string. $ means end. And we replacing here }\]*$ with just }.

Upvotes: 2

Related Questions