Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract directory path from file path?

Tags:

bash

In Bash, if VAR="/home/me/mydir/file.c", how do I get "/home/me/mydir"?

like image 717
Talespin_Kit Avatar asked May 25 '11 07:05

Talespin_Kit


People also ask

How can I extract the folder path from file path in Python?

Use os. path. dirname() to get the directory folder (name) from a path string.

What is absolute path extract directory?

Techopedia Explains Absolute PathAn absolute path always contains the root elements and the complete list of directories to locate the specific file or folder. All the information required to locate the file or folder is available in the absolute path.

How do I get the shell directory path?

2.1. To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.


1 Answers

dirname and basename are the tools you're looking for for extracting path components:

$ VAR='/home/pax/file.c' $ DIR="$(dirname "${VAR}")" ; FILE="$(basename "${VAR}")" $ echo "[${DIR}] [${FILE}]" [/home/pax] [file.c] 

They're not internal bash commands but they are 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.

like image 65
paxdiablo Avatar answered Sep 22 '22 05:09

paxdiablo