In Bash, if VAR="/home/me/mydir/file.c"
, how do I get "/home/me/mydir"
?
480
votes
8 Answers
753
votes
dirname
and basename
are the tools you're looking for for extracting path components:
$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c
They're not internal Bash commands but they're part of the POSIX standard - see dirname
and basename
. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash
.
111
votes
33
votes
On a related note, if you only have the filename or relative path, dirname
on its own won't help. For me, the answer ended up being readlink
.
fname='txtfile'
echo $(dirname "$fname") # output: .
echo $(readlink -f "$fname") # output: /home/me/work/txtfile
You can then combine the two to get just the directory.
echo $(dirname $(readlink -f "$fname")) # output: /home/me/work
7
votes
5
votes
5
votes
1
votes
1
votes
You could try something like this using approach for How to find the last field using 'cut':
Explanation
rev
reverses/home/user/mydir/file_name.c
to bec.eman_elif/ridym/resu/emoh/
cut
uses/
as the delimiter, and chooses the second field, which isridym/resu/emoh/
, which deletes string up to the first occurrence of/
- lastly, we reverse it again to get
/home/user/mydir
$ VAR="/home/user/mydir/file_name.c"
$ echo $VAR | rev | cut -d"/" -f2- | rev
/home/user/mydir