Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get only the file name using find command on Linux?
The Linux find command is one of the most widely used utilities that allows us to traverse a file hierarchy. It is primarily used to locate specific files or directories, and we can combine it with various flags and options to perform complex operations.
Let's explore a basic example of the find command to understand how it works.
In the example below, we are searching for a specific file named sample.sh in the current directory:
find sample.sh
Output
sample.sh
If the find command locates the file, it prints the file path. If the file is not found, the command terminates without output.
Getting Only File Names with GNU Find
When you want to extract only the file names without their full paths, GNU find provides the -printf option with format specifiers.
Use the following command in a GNU-compatible terminal:
find ./ -type f -printf "%f<br>"
Command Breakdown
./− Search in the current directory-type f− Find only files (not directories)-printf "%f− Print only the basename of each file followed by a newline
"
Output
file1.txt document.pdf script.sh image.jpg data.csv
Alternative Method for Non-GNU Systems
If you're using a non-GNU system (like macOS or BSD), the -printf option may not be available. In such cases, you can use the following alternatives:
Using basename with find
find ./ -type f -exec basename {} \;
Using a shell script approach
Create a shell script that extracts filenames using parameter expansion:
#!/bin/bash
for file in *; do
if [ -f "$file" ]; then
echo "${file##*/}"
fi
done
Save this script as getfilenames.sh, make it executable, and run it:
chmod +x getfilenames.sh ./getfilenames.sh
Advanced Examples
Finding specific file types
find ./ -name "*.txt" -printf "%f<br>"
Finding files in subdirectories
find /home/user/Documents -type f -printf "%f<br>"
Comparison of Methods
| Method | Compatibility | Performance | Complexity |
|---|---|---|---|
| find -printf | GNU only | Fast | Simple |
| find -exec basename | Universal | Slower | Medium |
| Shell script | Universal | Fast | Complex |
Conclusion
The find command with -printf "%f is the most efficient method to extract only filenames on GNU systems. For non-GNU systems, using
"find -exec basename provides a portable solution. Choose the method that best fits your system compatibility and performance requirements.
