Coder Perfect

How can I use Linux’s ‘search’ command to simply get the file name?

Problem

I’m using find to find all files in a directory, and I’m getting a list of paths as a result. However, I simply require file names. For example, if I get./dir1/dir2/file.txt, I want to receive file.txt.

Asked by marverix

Solution #1

You can do this using the -printf parameter in GNU find, for example:

find /dir1 -type f -printf "%f\n"

Answered by SiegeX

Solution #2

You can also use basename: if your find doesn’t offer a -printf option.

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

Answered by Kambus

Solution #3

If you’re using GNU find out more.

find . -type f -printf "%f\n"

Alternatively, you can use a programming language like Ruby(1.9+).

$ ruby -e 'Dir["**/*"].each{|x| puts File.basename(x)}'

If you fancy a bash (at least 4) solution

shopt -s globstar
for file in **; do echo ${file##*/}; done

Answered by kurumi

Solution #4

Use -execdir to keep the current file in a specific location, such as:

find . -type f -execdir echo '{}' ';'

Instead of, you can use $PWD. (On some systems, an extra dot in the front will not appear.)

If you still have an extra dot, you can alternately run:

find . -type f -execdir basename '{}' ';'

When + is used instead of ;, each invocation of utility is replaced with as many pathnames as possible. To put it another way, it will output all filenames on a single line.

Answered by kenorb

Solution #5

It can be difficult to use basename if you merely want to do something with the filename.

For example this:

find ~/clang+llvm-3.3/bin/ -type f -exec echo basename {} \; 

will just echo basename /my/found/path. Not what we want if we want to execute on the filename.

However, you can xargs the output. To kill files in a directory based on their names in another directory, for example:

cd dirIwantToRMin;
find ~/clang+llvm-3.3/bin/ -type f -exec basename {} \; | xargs rm

Answered by j03m

Post is based on https://stackoverflow.com/questions/5456120/how-to-only-get-file-name-with-linux-find