How to extract the path to the file

12

In a variable containing 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)

What results in ficheiro.pdf in variable filename .

How can we just extract the path to the file?

    
asked by anonymous 26.03.2015 / 11:20

1 answer

11

I think this is enough:

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

Note: because this is a bash parameter handling, it is not "portable" for any shell .


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

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


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

filenamepath="/caminho/para/ficheiro.pdf"
filepath='echo $filenamepath  | sed 's|\(.*\)/.*||' '
    
26.03.2015 / 11:29