michael
michael

Reputation: 397

Sed substitution with negative lookahead regex

I have a use case to add attribute:: to field name_[0-9][0-9]: but some field already have attribute::, so i need to only add attribtue:: to name_[0-9][0-9]: that not followed by attribute::

I have tried this:

sed  -n  's/name_[0-9][0-9]:(?!attribute::)/&attribute::/p' out

Which i test on online regex debugger that the regex should be what i need, but actually this doesn't match if i give name_01:abc

Upvotes: 5

Views: 5212

Answers (2)

tripleee
tripleee

Reputation: 189327

"Online regex debuggers" often don't tell you which precise regex dialect they test for; and if they tell you that, you need to know which dialect your sed supports.

You are trying to use a Perl regex feature which is not supported out of the box in any sed I am aware of, but of course, it's eminently well-supported in Perl.

perl -ne 's/name_[0-9][0-9]:(?!attribute::)/$&attribute::/ and print' out

Upvotes: 7

George Vasiliou
George Vasiliou

Reputation: 6335

$ cat file1
name_12:
name_34:attribute::
name_56:

$ sed '/:attribute::/n; s/name_[0-9][0-9]:/&attribute::/g' file1
name_12:attribute::
name_34:attribute::
name_56:attribute::

n : read the next line.

Upvotes: 2

Related Questions