Searching for files and text

From packets2photons
Jump to navigation Jump to search

These are my notes on how to best search for files and text on filesystems.

Searching for filenames

To search for a file name containing certain characters you can use

find /path/to/where/you/search/from -name "*.extension"

Searching for text

To search for text within a certain structure you can adapt the following.

find /path/to/where/you/search/from -type f -exec grep -H 'text-to-find-here' {} \;

Or you can use grep:

grep -r "string" /path

To show the lines surrounding the string match:

grep -r -C 3 foo README.txt

Modification and creation dates

To search for the most recently modified file:

find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

To search for the oldest creation date:

find /path/to/where/you/search/from -type f -printf '%T+ %p\n' | sort | head -n 20

To find a file of a certain size for example 68 bytes

find /path/to/where/you/search/from -type f -size 68c -exec ls {} \;

To find files 512k you could use:

find /path/to/where/you/search/from -type f -size +512k -exec ls -lh {} \;

To find the largest files in the filesystem

du -a /path/to/where/you/search/from | sort -n -r | head -n 20

I use the following on the command line to look for frequent element. You need to use your brain to filter the signal from the noise but it can be useful to identify uncommonly frequent IP addresses, MAC addresses and usernames et cetera.

sed -e 's/\s/\n/g' < file_of_interest.txt | sort | uniq -c | sort -nr | head  -200

Find the largest file in a directory

The following will search a directory of your choosing and find the largest 20 files

du -a /path/to/your/directory/ | sort -n -r | head -n 20

Find files with a certain extension

The following will find files with a certain extension.

find . -type f -name "*.txt"