[Linux](EN) Find file or directory using find command
Use find command in specific directory(path) to find file or directory
Environment and Prerequisite
- Linux base system
- Bash shell(/bin/bash)
What is find?
find
find
: search for files in a directory hierarchy- Below are examples of find command usages
# Basic Usage
$ find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression]
# Example1
$ find .
.
./test2.txt
./test_in
./test_in/another_test.txt
./pid_test_shell.sh
./test.txt
./tools
# Example2
$ find ./ -name "*.txt"
./test2.txt
./test_in/another_test.txt
./test.txt
# Example3
# -L option follow symbolic link
$ find -L ./ -name "*.sh"
./pid_test_shell.sh
./tools/upgrade_packages.sh
./tools/run_jupyter_notebook.sh
./tools/install_packages.sh
Examples
Find file using with grep
- Use pipe and grep command
find path | grep file_name
$ find . | grep test.txt
./anaconda3/pkgs/pylint-1.7.4-py36hb9d4533_0/lib/python3.6/site-packages/pylint/test/functional/using_constant_test.txt
./anaconda3/lib/python3.6/site-packages/pylint/test/functional/using_constant_test.txt
./test/test_in/another_test.txt
./test/test.txt
./.pyenv/versions/3.5.3/lib/python3.5/test/test_doctest.txt
./.pyenv/versions/3.5.2/lib/python3.5/test/test_doctest.txt
./.pyenv/versions/3.6.1/lib/python3.6/test/test_doctest.txt
Find file using file name
- Use command with
-name
find path -name file_name
$find . -name test.txt
./test/test.txt
Search by following symbolic link
- Use command with
-L
$ ls -l
total 16
-rwxrwxr-x 1 twpower twpower 119 May 6 18:36 pid_test_shell.sh
-rw-rw-r-- 1 twpower twpower 8 May 6 18:30 test2.txt
drwxrwxr-x 2 twpower twpower 4096 May 26 23:31 test_in
-rw-rw-r-- 1 twpower twpower 84 May 6 18:31 test.txt
lrwxrwxrwx 1 twpower twpower 20 May 26 14:53 tools -> /home/twpower/tools/
$ find ./ -name "*.sh"
./pid_test_shell.sh
$ find -L ./ -name "*.sh"
./pid_test_shell.sh
./tools/upgrade_packages.sh
./tools/run_jupyter_notebook.sh
./tools/install_packages.sh
Search file contents using with xargs
- Use find, pipe, xargs and grep command.
find . -name "*.txt" | xargs grep "He"
$ find . -name "*.txt" | xargs grep "He"
./test2.txt:Hello
./test2.txt:Hellot
./test2.txt:tHello