http://www.perlmonks.org?node_id=924385

cdlaforc has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I'm trying to do the below substitution creating 4 back references and putting a 0 between them. I usually use ${1} syntax instead of \1, but I am running this command via ssh and this is not working. Because of this I don't know what to do between the \2 and 0 to make sure the second back reference is recognized. Any ideas? Thanks, Chris.
perl -pi -e 's/^(ISA\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~)(..........) +(....).(\~.*)$/\1\20\3\4/' PB385930.P0

Replies are listed 'Best First'.
Re: problems with backreference
by ikegami (Patriarch) on Sep 06, 2011 at 15:33 UTC

    \1 is a regular expression pattern that matches what the first capture captured. It makes no sense to use it outside of regular expressions as you did.

    Perl script:

    s/^(ISA\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~)(..........)(....).(\~.*) +$/$1${2}0$3$4/

    Perl command:

    perl -i -pe's/^(ISA\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~)(..........)( +....).(\~.*)$/$1${2}0$3$4/' PB385930.P0

    ssh command:

    ssh ... 'perl -i -pe'\''s/^(ISA\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~.*?\~)( +..........)(....).(\~.*)$/$1${2}0$3$4/'\'' PB385930.P0'

    Note the ' needed to be escaped when placed inside another ' literal.

Re: problems with backreference
by norbert.csongradi (Beadle) on Sep 06, 2011 at 14:21 UTC

    Please give some info about how you send it over SSH, there should be some problem there (in shell escapes I think)

    This should be better to send over SSH (not tested!):

    ssh user@host 'perl -pi -e "s/^(ISA~.*?~.*?~.*?~.*?~.*?~.*?~.*?~)(.... +......)(....).(~.*)\$/\\1\\20\\3\\4/"'

    Double escapes of \ chars become one backslash on the remote side, no need to escape tilde. Anyway, better to see your version still.