Search code examples
regexperlescapingslash

How to escape slashes in Perl text used in a regular expression?


end_date=$(date +"%m/%d/%Y")
/usr/bin/perl -pi -e "s/_end_date_/${end_date}/g" filename

I want to replace string '_end_date_' with the current date. Since the current date has slashes in it (yes, I want the slashes), I need to escape them. How can I do this?

I've tried several ways, like replacing slashes with "/" using sed and Perl itself, but it didn't work. Finally I used 'cut' to break date in 3 parts and escaped slashes, but this solution doesn't look good. Is there a better solution?


Solution

  • In Perl you can choose which character to use to separate parts of a regular expression. The following code will work fine.

    end_date = $(date +"%m/%d/%Y")
    /usr/bin/perl -pi -e "s#_end_date_#${end_date}#g" filename
    

    This is to avoid the 'leaning toothpick' syndrome with / alternating.