Search code examples
bashperlprintfquoting

Quoting pb with the Perl print function


I want to grep a paragraph in a list a files using 2 regexp which are inside 2 bash variables, here is what I type :

$ startRegExp=function.toto
$ endRegExp=^}
$ set -x
$ perl -ne "print '\$ARGV:\$_' if /$startRegExp/ ... /$endRegExp/" .bash_functions*

But this is what I get :

+ perl -ne 'print '\''$ARGV:$_'\'' if /function.locate/ ... /^}/' .bash_functions .bash_functions.AV .bash_functions.Darwin .bash_functions.Debian .bash_functions.Linux .bash_functions.build .bash_functions.mpv .bash_functions.ytdl
$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_$ARGV:$_

Can you help me ?


Solution

  • Single quotes in Perl don't interpolate variables. Send the variables to the script through the environment so they become first class citizens and you can use any characters in them:

    s=$startRegExp e=$endRegExp perl -ne 'print "$ARGV:$_" if /$ENV{s}/ ... /$ENV{e}/'
    

    Note that if the file doesn't contain the closing }, perl will continue printing the next file. This can be fixed by changing the right range operand to (/$ENV{e}/ || eof).