I need to create a list of files in a directory and all of its subdirectories. I've used
find . -type f
to get the list of files, but I only need the file name, not the path that leads to it.
So instead of returning this:
./temp2/temp3/file3.txt
./temp2/file2.txt
./file.txt
I need to return
file3.txt
file2.txt
file.txt
find . -type f -exec basename {} \;
或更好:
find . -type f -printf "%f\n"
You can use printf
option in gnu find
:
find . -type f -printf "%f\n"
For non-gnu find
use -execdir
and printf
:
find . -type f -execdir printf "%s\n" {} +
find . -type f | xargs basename
The command basename
strips the directories and outputs only the file name. Use xargs
to chain the output of find
as the input of basename
.
Late answer :)
The -printf "%f"
is the best solution, but the printf
is available only in the GNU find. For example on the OS X (and probably FreeBSD too) will print:
find: -printf: unknown primary or operator
for such cases, myself prefer the following
find . -type f | sed 's:.*/::'
It is faster (on the large trees) as the multiple basename
execution.
Drawback, it will handle only filenames without the \\n
(newline) in the filenames. For handling such cases the easiest (and most universal - but slow) way is using the basename
.
You can also use perl, like:
perl -MFile::Find -E 'find(sub{say if -f},".")'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.