user1812457
user1812457

Reputation:

Insert between each occurrence of two characters

If I can have somewhere in my input a series of two or more characters (in my case, >), how can I insert something between each occurrence of >?

For example: >> to >foo>, but also: >>> to >foo>foo> and: >>>> to >foo>foo>foo>.

Using 's/>>/>foo>/g' gives me of course >foo>>foo>, which is not what I need.

In other words, how can I push a character back to the pattern space, or match a character without consuming it (does that make any sense?)

Upvotes: 3

Views: 176

Answers (2)

glenn jackman
glenn jackman

Reputation: 246837

Using Perl, you can do it iteratively

$ echo '>>>>' | perl -pe 's/>>/>foo>/ while />>/'
>foo>foo>foo>

or use a look-ahead assertion, which does not consume the 2nd >

$ echo '>>>>' | perl -pe 's/>(?=>)/>foo/g'
>foo>foo>foo>

Upvotes: 1

Vivek
Vivek

Reputation: 2020

This should also work

sed ':b; s/>>/>foo>/; tb'

Upvotes: 1

Related Questions