I want to use sed for extracting the file name after the last occurrence of /.

For example /usr/bin/file.txt and the output should be file.txt

  • Is this an assignment/homework? I can't see any other reason as to why you absolutely need to use sed. – Nasir Riley Nov 7 '18 at 0:50

You don't need to use sed; you can use the basename command to return the filename part:

> basename /usr/bin/top

If you definitely want to use sed, this works with GNU sed 4.5:

sed 's/^.*\/\([^/]\+\)$/\1/'
| improve this answer | |
  • 1
    no need to anchor the .* to the beginning -- it's greedy and will match as much as it can; ditto the trailing part – Jeff Schaller Nov 7 '18 at 1:11

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.