Grep, finding, searching and deleting files in Linux

Posted under » Linux on 26 December 2011

Grep is good for finding strings. Use grep to search for lines of text that match one or many regular expressions, and outputs only the matching lines. One of the most useful commands on Linux with a variety of uses.

Most basic usage

grep 'string' *.txt
grep --color 'data' fileName.txt

Slighty more defined and recursively i.e. read all files under each directory

grep 'comprehend' --include=*.txt /var/zim/ -r
// i stands for ignore case
// r stands for recursive.
// l stands for "show the file name, not the result itself"
// c stands for count
// n stands for line number
grep -ril "syndrome" /home/dude/Doc/

If the recursive bit doesn't give the complete result, then go root of the directory and

$ grep "leaning" -ril

Pipes or | can be use for ls and other commands.

History is a common use for me

history | grep firefox

PS

ps axuwww | grep python

Exclude some words

grep -v "handsome" lky.txt | grep "bastardy"

Use grep to search 2 different words. Use the egrep command which is regex like. w = whole words

$ egrep -w 'word1|word2' /path/to/file
$ egrep 'word1|word2' /path/to/file
$ egrep '(s|h)d[a-z]' /path/to/file

Related

Find every file under the directory /usr starting in "file".

find /usr -name 'file*'
find /var/www -name '.*' // all the hidden files
find . -name 'bazaar'
find /var/www -name bazaar

Find every file owned by a user (or group).

find ./ -group zawwin

To see all files modified on the 24/Jun/2020 in the current directory.

find . -type f -newermt 2020-06-24 

Deleting folders and files recursively.

find . -name '._*' -exec rm -rf {} \;
find . -type d -name .svn -exec rm -rf {} \; // delete svn all files on directories
find . -type f -name "*.sw[klmnop]" -delete // delete gedit swp files or
find . -name '*.swp' -print0 | xargs -0 rm -i --

This script would work on any search type; simply replace ".svn" with the search of your choosing but be careful: if your search term is too general, you may end up deleting a bunch of stuff you don't want to!

Also You can also google whereis or locate.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data