Linux grep and find command

LORY
2 min readApr 2, 2021

--

linux command with samples

Grep

find all log files

 find . | grep .log$

count how many log files

ls /var/log | grep -c .log
11

grep keyword in file

grep -e Started* /var/log/boot.log

grep keyword in file and use -n to print line number

grep -e Started* /var/log/boot.log -n

grep recursively

grep -e Started* /var/log -r

Find

find file by name(pattern)

find . -name boot.log
./var/log/boot.log
find . -name *.log
./var/log/tuned/tuned.log
./var/log/audit/audit.log

search in log folder with case insensitive

find /var/log -iname *Network.*log
/var/log/vmware-network.2.log
/var/log/vmware-network.1.log
/var/log/vmware-network.log

search all folders under log

find /var/log -type d
/var/log
/var/log/tuned
/var/log/audit
..

other options
d — directory or folder
f — normal file
l — symbolic link

find and delete (no confirmation)

find /var/log -name *network.log -delete

find then delete files with confirmation

find /var/log -iname *network*1.log -exec rm -i {} \;

search logs where last modified(changed) time is within one day

find /var/log -mtime -1
find /var/log -ctime -1

negative means less than days(-1 less than 1 day); positive means days ago (5 means 5 days ago).

find logs changed within 30 mins

find /var/log -type f -mmin -30
/var/log/audit/audit.log
/var/log/messages
/var/log/vmware-vmsvc-root.log
/var/log/cron

use ls to see what exact time are they modified

find /var/log -type f -mmin -30 | xargs ls -l
-rw — — — -. 1 root root 151063 Apr 2 03:06 /var/log/audit/audit.log
-rw — — — -. 1 root root 1614 Apr 2 03:01 /var/log/cron
-rw — — — -. 1 root root 278547 Apr 2 03:05 /var/log/messages
-rw — — — -. 1 root root 67238 Apr 2 03:20 /var/log/vmware-vmsvc-root.log

find all files > 10mb and < 50mb and print out each file detail

find . -type f -size +10M -size -50M | xargs ls -l

search files by ownership(-user), group(-group) ,permission(-perm) code

find /var/log -user root | xargs ls -l
find /var/log -group root | xargs ls -l
find /var/log -type d -perm 755 | xargs ls -l

find empty files and folders

find . -empty
find empty files
find . -type f -empty

find+grep to search keyword in multiple files

find /var/log -type f -iname *log | xargs grep boot

--

--

LORY

A channel which focusing on developer growth and self improvement