understack
understack

Reputation: 11580

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?

Upvotes: 3

Views: 5756

Answers (4)

Peter Tillemans
Peter Tillemans

Reputation: 35341

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.

Upvotes: 17

justintime
justintime

Reputation: 3631

Building on Axeman's answer, the following works for me :

 perl -MPOSIX=strftime  -p -e'$ed=strftime( q[%m/%d/%Y], localtime()) ;s/_end_date_/$ed/'

A few things to note

  • The quotemeta isn't needed because the compiler isn't looking for a / in the variable $ed.
  • I have used single quotes ' rather than " as otherwise you end up having to quote $
  • I prefer using -MPOSIX=strftime to BEGIN { use POSIX qw<strftime> }

Upvotes: 0

Axeman
Axeman

Reputation: 29854

I would recommend changing the delimiter, but you can almost always get by with quotemeta:

/usr/bin/perl -pi -e "my \$ed=quotemeta('${end_date}');s/_end_date_/\$ed/g" filename

But you also have this route:

/usr/bin/perl -pi -e 'BEGIN { use POSIX qw<strftime>; $ed=quotemeta(strftime( q[%m/%d/%Y], localtime())); } s/_end_date_/$ed/'

which does the same thing as your two lines.

Upvotes: 1

Pedro Silva
Pedro Silva

Reputation: 4700

Use a different s delimiter: s{all/the/slashes/you/want/}{replacement}.

Upvotes: 6

Related Questions