Home > Blockchain >  How to use back references at addresses with extended regular expressions in sed in macOS
How to use back references at addresses with extended regular expressions in sed in macOS

Time:07-26

I'd like to use back references at addresses with extended regular expressions in sed in macOS (version 12.4).

With basic regular expressions, I can use back references (that is, this is an expected result):

% echo -e 'Foo,Foo\nFoo,Bar' | sed '/\(Foo\),\1/s//__SAME__/'
__SAME__
Foo,Bar

However, with extended regular expressions, the following back reference does not work:

% echo -e 'Foo,Foo\nFoo,Bar' | sed -E '/(Foo),\1/s//__SAME__/'
Foo,Foo
Foo,Bar

Can I use back references at addresses with extended regular expressions with some modifications?

The difference in back references between basic and extended regular expressions seems odd. Is this a bug?

For your information, both of the above commands work well with GNU sed 4.8.

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

As mentioned in my comments above that BSD sed in ERE mode doesn't support back-references like \1. Wiktor has also attached a reference that states clearly that POSIX standard doesn't support it.

As I commented above a better alternative would be to use perl like this:

perl -pe 's/(Foo),\1/__SAME__/' file

CodePudding user response:

According to regular-expressions.info "POSIX Extended Regular Expressions", the

The POSIX standard does not define backreferences. Some implementations do support \1 through \9, but these are not part of the standard for ERE. ERE is an extension of the old UNIX grep, not of POSIX BRE.

Hence, a Perl alternative here is quite a viable approach.

CodePudding user response:

This might work for you:

echo -e ',s/\\(Foo\\),\\1/__SAME__/\nwq' | ed -s file -

This pipes ed commands into an invocation of ed and amends file.

N.B. I don't use MacOs but according to its manual it uses FreeBSD which accomodates back references in standard unix editor ed.

  • Related