Tuesday, November 22, 2011

UNIX: Search for files

The grep command helps you to search with the text pattern in the file or filenames. It helps you to find the files by their content. Whereas find command helps you in searching for the files.

Examples:

1. Print all directories and filenames under the current directory
bash-3.00$ find . (dont miss the dot here)
.
./wm-dev
./wm-dev/bin
./wm-dev/bin/exec.sh
./wm-dev/config

2. Print all directories and filenames under the current directory/directory

bash-3.00$ find wm-dev
wm-dev
wm-dev/bin
wm-dev/bin/exec.sh
wm-dev/config

You can notice that the list printed starts with the searching directory.

3. Print all directories and filenames under the current directory/directory/directory
bash-3.00$ find wm-dev/bin
wm-dev/bin
wm-dev/bin/exec.sh

4. From the root directory search for a filename of the given pattern 'exec.sh'
bash-3.00$ find . | grep 'exec.sh'
./wm-dev/bin/exec.sh
./wm-cn/bin/ca7-orig/exec.sh.orig
./wm-cn/bin/exec.sh
./wm-cn/bin-old/exec.sh
./wm-cn-dev/bin/exec.sh
./wm-prod-dev-old/bin/exec.sh
./wm-prod-dev/bin/exec.sh
./wm-prod-dev/bin/exec.sh_090909

Another one alternative for the above option.
bash-3.00$ find . -name "exec.sh"
./wm-dev/bin/exec.sh
./wm-cn/bin/ca7-orig/exec.sh.orig
./wm-cn/bin/exec.sh
./wm-cn/bin-old/exec.sh
./wm-cn-dev/bin/exec.sh
./wm-prod-dev-old/bin/exec.sh
./wm-prod-dev/bin/exec.sh
./wm-prod-dev/bin/exec.sh_090909

Find files that have been modified in last 5 days (with minus)
find . -mtime -5

Find files that was modified exactly 5 days before (without minus)
find . -mtime 5

Find files that was not modified for past 5 days (with +)
find . -mtime +5

Find files in multiple directories.
find usr bin -name "*.cp"

List the directories alone.
find . -type d

List the files alone.
find . -type f


Hope this is helpful. Thanks Phoenix...

No comments:

Post a Comment