How do I return only file names from the find command?

I'm looking to get a list of just file names (without the rest of the path) when executing the find command from a terminal. How do I accomplish this on the mac?

0

7 Answers

With basename:

find . -type f -exec basename {} \;

4

Evilsoup mentioned that what was posted doesn't work for spaced file names. So instead you could use:

find . -type f -print0 | while IFS= read -r -d '' filename; do echo ${filename##*/}; done
2

With GNU find, you can do:

 find ~/tmp/ -printf "%f\n"

This is probably worth trying in OS X too.

3

There is a better way to strip everything but the last portion of a file path; with awk. It is better because awk is not executed once for every file. In some cases this matters.

find ~/tmp/ -type f | awk -F/ '{ print $NF }'

We look only for files in ~/tmp and we get a list where every entry is separated by slashes. Hence, we use a slash as the field separator (-F/) and print the field parameter ($1..$9) that corresponds to the last field ($NF).

2

EDIT:

Using sed:

$ find . -type f | sed 's/.*\///'

Using the xargs command, as mentioned in the response of @nerdwaller

$ find . -type f -print0 | xargs --null -n1 basename
3

You can call sh from within find's -exec option and avoid using uneccesary pipes. This also has the advantage that you don't need to worry about funny filenames (spaces, newlines, etc.):

find . -type f -exec sh -c 'echo "${0##*/}"' {} \;

What about this:

find … | egrep -o -e '[^/]+$'

Advantage: Only exactly one additional process is spawned, not one for each result.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like