How to extract the path to the file

Asked

Viewed 129 times

12

In a variable that contains the path to a file and its name, the file name can be extracted as follows:

#!/bin/bash
filenamepath="/caminho/para/ficheiro.pdf"
filename=$(basename $filenamepath)

Which results in ficheiro.pdf in the variable filename.

How can we extract only the path to said file ?

1 answer

11


I think this is enough:

filenamepath="/caminho/para/ficheiro.pdf"
filepath=${filenamepath%/*}

Note: because it is a parameter treatment of bash, is not "portable" to any shell.


If you prefer a solution analogous to the question, using external commands, we have the dirname, which is the "natural pair" of basename:

filenamepath="/caminho/para/ficheiro.pdf"
filename=$(dirname $filenamepath)


Alternatively, here is a syntax using the sed and demonstrating the use of backticks to pick up the output of another command:

filenamepath="/caminho/para/ficheiro.pdf"
filepath=`echo $filenamepath  | sed 's|\(.*\)/.*|\1|' `

Browser other questions tagged

You are not signed in. Login or sign up in order to post.