Monday, January 27, 2014

Useful Unix File Find Commands


Following are some bunch of commands that might be useful if you want to find files in unix/linux.

Large Files

Find files larger than 10MB in the current directory downwards…
find . -size +10000000c -ls

Find files larger than 100MB…
find . -size +100000000c -ls

Old Files

Find files last modified over 30days ago
find . -type f -mtime 30 -ls

Find files last modified over 365days ago
find . -type f -mtime 365 -ls

Find files last accessed over 30days ago
find . -type f -atime 30 -ls

Find files last accessed over 365days ago
find . -type f -atime 365 -ls

Find Recently Updated Files

There have been instances where a runaway process is seemingly using up any and all space left on a partition. Finding the culprit file is always useful.
If the file is being updated at the current time then we can use find to find files modified in the last day.
find  . -type f -mtime -1 -ls

Better still, if we know a file is being written to now, we can touch a file and ask the find command to list any files updated after the timestamp of that file, which will logically then list the rogue file in question.

touch testfile
find .  -type f -newer testfile -ls

Finding tar Files

A clean up of redundant tar (backup) files, after completing a piece of work say, is sometimes forgotten. Conversely, if tar files are needed, they can be identified and duly compressed (using compress or gzip) if not already done so, to help save space. Either way, the following lists all tar files for review.
find . -type f -name "*.tar" -ls
find . -type f -name "*.tar.Z" -ls

Large Directories

List, in order, the largest sub-directories (units are in Kb)…
du -sk * | sort -n

Sometimes it is useful to then cd into that suspect directory and re-run the du command until the large files are found.

Removing Files using Find

The above find commands can be edited to remove the files found rather than list them. The “-ls” switch can be changed for “-exec rm {}\;”=.

find . -type f -mtime 365 -exec rm {} \;

Running the command with the “-ls” switch first, is always prudent to see what will be removed.

The “-ls” switch prints out summary information about the file (like owner and permissions). If just the filename is required then swap “-ls” switch for “-print”.

Find and Replacing words using Find

The below find command finds and replaces the word 'apple' with 'orange' in all the occurrences in each files in the test directory.

find ./test -exec sed -i 's/apple/orange/g' {} \;

No comments:

Post a Comment