Useful find and grep command line snippets

A collection of find and grep commands that I've used over the years

Written 4 years ago on Apr 7, 2017

A well written find command can get a shed tonne done, here's a few of my favourites...


Search for a string recursively in all files in and below current dir

 find -type f -print0 | xargs -0 grep -i 'Cowshed'

This can also be done with the -exec action in the find command

find -type f -exec grep -i 'Cowshed' {} \;

Aim this search at a different base directory by providing it as the first argument

find /home/dir/ -type f ........

Find and delete

Find jpgs that are 724 bytes - count the total

find . -name "*.jpg" -size 724c | wc -l

Find the same files and delete them

find . -name "*.jpg" -size 724c -exec rm {} \;

PHP searches

Find PHP short tags

find -type f -print0 | xargs -0 grep -rn "&lt?[^p]"

Root out calls to the deprecated mysql_ functions

find -type f -print0 | xargs -0 grep -i 'mysql_query'

Root out calls to the deprecated eregi_ functions

find -type f -print0 | xargs -0 grep -i 'eregi_'

Find all _POST and _GET references in files, very useful for when you've got some time to make sure there aren't any silly sanitising errors, dump results in a file to go through

grep -rnw . -e "_POST" -e "_GET" > TOFIX.txt

r = recursive, n = prefix line numbers, w = word-regexp search string must be preceded or followed by a non-word character, ie a $ in this case.

Time based

Find all files modified yesterday, the -mtime option expects a parameter n where n = n * 24 hours, so in this case 1 * 24 hours.

find . -type f -mtime 1

Copy files modified in last 7 days, preserve dir structure

find . -mtime -7 -exec cp --parents \{\} tempOUT/ \; 

The + - options for -mtime simply mean +1 = greater than 1 day ago, -1 = less than 1 day ago. So find . -mtime 0 is the same as -mtime -1... some examples from

find . -mtime +0 # find files modified greater than 24 hours ago
find . -mtime 0 # find files modified between now and 1 day ago
# (i.e., in the past 24 hours only)
find . -mtime -1 # find files modified less than 1 day ago (SAME AS -mtime 0)
find . -mtime 1 # find files modified between 24 and 48 hours ago
find . -mtime +1 # find files modified more than 48 hours ago

Article Category Tags

Click one to see related articles hand-written by Cowshed Works


Want to discuss your next web project?

We're happy to host meetings at the Cowshed or via conference call, we're equally happy to come and meet you to discuss your project.

Just drop us a line and we'll get it booked in and get the ball rolling.

Cowshed Works

What our clients say...