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
Author by
iwan
Updated on November 25, 2020Comments
-
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 about 12 years
file=${path##*/}
will work inksh
as well; in fact, bash borrowed this feature from ksh. Anysh
on any Linux system is likely to support this, too. -
TimGJ almost 10 yearsI've tried this and basename seems to be falling over on paths where there is a space in the name.
-
Keith Thompson almost 10 yearsIt should be enclosed in double quotes to avoid problems with funny characters in the file name:
file="$(basename $path)"
orfile="${path##*/}"
-
tonymarschall over 6 yearskeep an eye on the times ... answered Apr 12 '12 at 13:15 vs Apr 12 '12 at 13:16
-
thebunnyrules over 6 yearsYou 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 over 4 yearsThat is the reverse what OP is asking for:
dirname any/path/abc.txt
->any/path
, while they were asking forabc.txt
-
Merlin over 2 yearsThis is really useful, and basename can remove file extensions as well.