April 26, 2024

Searching for files by patterns in name/contents

A common and task of someone using the Linux Command Line (shell) are to search for files/directories with a certain name or containing certain text. There are 2 commands you should familiarise yourself with in order to
accomplish this:

Find files by name
find /var/www -name ‘*.css’

This will print out the full path/filename to all files under /var/www that end in .css. Example output:

/var/www/html/text-cursor.css
/var/www/html/style.css

For more info:

man find

Find files containing text
grep font /var/www/html/style.css

This will print all lines containing the pattern font in the specified file. Example output:

font-weight: bold;
font-family: monospace;

Another example:
grep font /var/www/html/

This doesn’t work as you’d hoped. You get:
grep: /var/www/html/: Is a directory

You need to grep recursively to make it work, using the -R option:
grep -R font /var/www/html/

Hey, nice! Check out the output of this one:

/var/www/html/admin/index.php: echo '<font color=red><b>Error: no dice</b></font><br/>';

/var/www/html/admin/index.php: echo '<font color=red><b>Error: try again</b></font><br/>';

/var/www/html/style.css: font-weight: bold; 
/var/www/html/style.css: font-family: monospace;

Notice that when to grep is matching multiple files, it prefixes the matched lines with the filenames. You can use the -h option to get rid of that if you want.

For more info:
man grep

Vedant Kumar

Currently I'm working as an Implementation Engineer, Started my career as an System Administrator - Linux. Additionally loves to explore new technologies and research about new open-source software that ease the development cycle.

View all posts by Vedant Kumar →

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

close

Ad Blocker Detected!

VEDANT EXPLAINS
We've noticed that you are using an ad blocker. Advertising helps fund our server cost and keep it truly independent. It helps to build our content creator team. So please disable your ad blocker, and help us to keep providing you with free- great content - for free. Thank you for your support.

Refresh