Notes Use of /1 in the substitution is deprecated. Use $1 instead. Use of {} for the delimiters only allows to not have to escape / thus making it all more readable -- but otherwise the same works when using / for delimiter and then escaping it inside.

Update

To also catch a lone ~/ (or /), the simplest change was to add that explicitly, /.*/ | /. In order to capture the (optinal) ~ in both cases there is a (non-capturing) grouping around this. Removed -w flag so no warnings are issued when the input string has no slashes at all, but only an empty line is printed.

Email codedump link for regex for capturing path from a string with optional character ~ (perl|awk|sed|..)