separate file and path in bash?

7

1

How can I separate the path and file elements in a bash loop like this?

for file in `find /my/path -name "*.ext"`
do
    #(path,onlyfile) = separate_path_and_file $file
    #dosomethingwith $onlyfile
done

719016

Posted 2012-07-02T08:02:08.153

Reputation: 2 899

Answers

10

You can't. But you can do them separately.

$ foo=/usr/local/bin/bar
$ echo "${foo##*/}"
bar
$ echo "${foo%/*}"
/usr/local/bin

Ignacio Vazquez-Abrams

Posted 2012-07-02T08:02:08.153

Reputation: 100 516

23

I would suggest dirname and basename:

for file in `find /my/path -name "*.ext"`
do
    path="$(dirname $file)"
    onlyfile="$(basename $file)"
    # ...
done

cYrus

Posted 2012-07-02T08:02:08.153

Reputation: 18 102

3This is much more readable than the accepted answer. – itsafire – 2015-09-02T09:55:58.837

and in case there are spaces in the file, i would add quotation around the $file. https://stackoverflow.com/questions/7194192/basename-with-spaces-in-a-bash-script

– Hermann Ingjaldsson – 2018-07-19T10:12:56.817

1In zsh of Windows Subsystem for Linux, path="$(dirname $file)" will change $PATH, then onlyfile="$(basename $file)" will print error basename: command not found – Weekend – 2018-08-22T10:12:40.403