How to substitute with basic regex with alternating signs?

Viewed 27

I want to do the following to all of the statements in the file:

Input: xblahxxblahxxblahblahx

Output: <blah><blah><blahblah>

So far I am thinking of using sed -i 's/x/</g' something.ucli

1 Answers

You can use

sed 's/x\([^x]*\)x/<\1>/g'

Details:

  • x - an x
  • \([^x]*\) - Group 1 (\1 refers to this group value from the replacement pattern): zero or more (*) chars other than x ([^x])
  • x - an x

See the online demo:

#!/bin/bash
s='xblahxxblahxxblahblahx'
sed 's/x\([^x]*\)x/<\1>/g' <<< "$s"
# => <blah><blah><blahblah>

If x is a multichar string, e.g.xyz, it will be easier with perl:

perl -pe 's/xyz(.*?)xyz/<$1>/g'

See this online demo.

Related