Useful find and grep command line snippets

By Gavin Phillips @ Cowshed Works Ltd

Blog Picture

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

Searches

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 "<?[^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 http://unix.stackexchange.com/questions/92346/why-does-find-mtime-1-only-return-files-older-than-2-days:


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

Author: Gavin Phillips
Published: Apr 7, 2017 (1 year ago)

Work with Cowshed:Works

Ready to start your next website or app project? Give us a call or send us an email.



© Cowshed Works Ltd: UK Staffordshire-based website design, build and management

VAT: 251 4480 22 - Registered in England: 10399485

Terms: Website | Service