Tuesday, May 28, 2019

Backreference in Perl vs sed


Perl uses $n (where n is a number) for backreferences; while sed uses \n.

For example, we want to switch the contents between #:# in this file:
#Hello:World#!
How #are:you#?

Using sed, we run command:
$ sed -n -e 's/#\([^:]*\):\([^#]*\)#/#\2:\1#/p' filename

Using perl, we can run command:
$ perl -p -e 's/#([^:]*):([^#]*)#/#$2:$1#/' filename

or:
$ perl -p -e 's/#([^:]*):([^#]*)#/#${2}:${1}#/' filename

The output will be:
#World:Hello#!
How #you:are#?

A few notes:
1. The backreference of sed can be only one digit. That means \10 will be \1 (the first reference) and a digit 0.
2. sed uses \( and \) to group while Perl uses ( and ) only.

No comments:

 
Get This <