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.

Thanks

link|improve this question
feedback

2 Answers

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.)

link|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
feedback

Is there a particular reason to not use awk?

echo $DIR | awk -F'\' '{ print $(NF-1) "\\" $NF }'
link|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
feedback

Your Answer

 
or
required, but never shown

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