Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to extract the filename and containing directory from a full path (DOS syntax). I need to do this using sed as it is part of a larger regular expression.

Example input: ..\home\test\somedir\anotherdir\myfile.txt

Expected output: anotherdir\myfile.txt

Any help would be greatly appreciated.


share|improve this question
up vote 1 down vote accepted

Just go at it methodically. You want to divide a line into three parts: an arbitrary prefix .*, and then twice a backslash followed by non-backslash characters \\[^\\]*. Capture what's after the next-to-last backslash and drop the rest.

printf %s "$dos_path" | sed 's/^.*\\\([^\\]*\\[^\\]*\)$/\1/'

(Beware of echo as some shells expand backslashes.)

share|improve this answer
Awesome works a treat, thanks. Yeah I probably could have got there on my own but my mind had turned to mush yesterday after reading and writing regular expressions all day! – Raoul Dec 21 '10 at 10:50

Is there a particular reason to not use awk?

echo $DIR | awk -F'\' '{ print $(NF-1) "\\" $NF }'
share|improve this answer
As I said in my question, it is part of a larger regular expression that I already have. I would have had to rewrite the rest of the regular expression in awk syntax in order to fit this in. Plus my awk knowledge is more-or-less non-existent unfortunately. – Raoul Dec 21 '10 at 10:59

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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