Grab the filename in Unix out of full path

61,886

Solution 1

In bash:

path=/this/is/could/be/any/path/abc.txt

If your path has spaces in it, wrap it in "

path="/this/is/could/be/any/path/a b c.txt"

Then to extract the path, use the basename function

file=$(basename "$path")

or

file=${path##*/}

Solution 2

basename path gives the file name at the end of path

Edit:

It is probably worth adding that a common pattern is to use back quotes around commands e.g. `basename ...`, so UNIX shells will execute the command and return its textual value.

So to assign the result of basename to a variable, use

x=`basename ...path...`

and $x will be the file name.

Solution 3

You can use dirname command

$ dirname $path

Solution 4

You can use basename /this/is/could/be/any/path/abc.txt

Share:
61,886
iwan
Author by

iwan

Updated on November 25, 2020

Comments

  • iwan
    iwan over 3 years

    I am trying to get "abc.txt" out of /this/is/could/be/any/path/abc.txt using Unix command. Note that /this/is/could/be/any/path is dynamic.

    Any idea?

  • sorpigal
    sorpigal about 12 years
    file=${path##*/} will work in ksh as well; in fact, bash borrowed this feature from ksh. Any sh on any Linux system is likely to support this, too.
  • TimGJ
    TimGJ almost 10 years
    I've tried this and basename seems to be falling over on paths where there is a space in the name.
  • Keith Thompson
    Keith Thompson almost 10 years
    It should be enclosed in double quotes to avoid problems with funny characters in the file name: file="$(basename $path)" or file="${path##*/}"
  • tonymarschall
    tonymarschall over 6 years
    keep an eye on the times ... answered Apr 12 '12 at 13:15 vs Apr 12 '12 at 13:16
  • thebunnyrules
    thebunnyrules over 6 years
    You answer is good, but if the designer wants the script to work with paths that have space, the first answer needs quotation marks around the $path, so: file=${basename "$path"} . I've made an edit of the answer to fix that but I think it needs your approval. @Keith Thompson, file="${basename $path}" wouldn't work, the quotes need to be on $path or the basename function won't work properly.
  • Marcono1234
    Marcono1234 over 4 years
    That is the reverse what OP is asking for: dirname any/path/abc.txt -> any/path, while they were asking for abc.txt
  • Merlin
    Merlin over 2 years
    This is really useful, and basename can remove file extensions as well.