So I have a file with contents in the following format,

randomString abc\/def/ghi/mno\/pq/r   abc\/def\/ghi/mno\/pq/r

My intention is to replace all occurrences of / with \/ between two alpha-numeric strings if the ending word does not have a \ or /, so ideally, it should be

randomString abc\/def\/ghi\/mno\/pq/r   abc\/def\/ghi\/mno\/pq/r

I was able to nearly achieve the result using this regEx

perl -pe 's/(\/\w+)\/(\w+\/|\w+\\)/$1\\\/$2/g' file

which is returning me

randomString abc\/def\/ghi/mno\/pq/r   abc\/def\/ghi\/mno\/pq/r

for some reason am not able to figure out why ghi/mno part of the string is not getting modified.

Am looking for a way to do this in perl command line.

1 Answer 1


You could use lookarounds to replace only those forward slashes that are:

  • (?<!\\) not preceded by a backslash
  • (?!\w+\s) not followed by word characters terminating in whitespace


echo 'randomString abc\/def/ghi/mno\/pq/r   abc\/def\/ghi/mno\/pq/r' |
  perl -pe 's;(?<!\\)/(?!\w+\s);\\/;g'
randomString abc\/def\/ghi\/mno\/pq/r   abc\/def\/ghi\/mno\/pq/r
  • Really appreciate this style, but really want to fix what was wrong with my regEx, am really trying to improve on that way! Thanks!
    – Inian
    Dec 14, 2016 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.