Knowledgebase

How to search for text in files via SSH

If you need to find something, but you don't know in which file it is, you can search for it through SSH with the grep command. It's very useful, for example, if you're looking for a string of code and you don't know in which file it is. The grep command will save you a lot of time, and will narrow down the search significantly. You can search for a word, a whole expression, a combination of symbols and letters, etc. In its simplest form use the command followed by the word/expression that you want to find and some criteria for the files to be searched (or the name of a particular file). For example:

grep "header logo" *.php

will search for the expression header logo in all PHP files in the current working directory (without its subdirectories). You can use just a wildcard instead of combining it with an extension type (e.g. .php) to search all the files in the current working directory:

grep "header logo" *

If there are any files that have the expression in them, they will be listed together with the line(s) containing that word/expression. There are also some useful options that you can combine with the command. For recursive searches use the -r option. For example:

grep -r "header logo" *.php

will search for the expression header logo in all PHP files that are in the current working directory and all its subdirectories. Keep in mind that in this case the grep command needs a lot of resources. So it's not bad if you have some idea of which folder might contain the file with the expression that you're looking for, instead of searching through your whole hosting account (especially if you have a lot of content uploaded on it). If you're searching through a lot of files, you might have to wait a bit until the search is complete.

By default, as we mentioned, the command lists not only the files containing the expression but also the line(s) in that file in which the expression occurs. To see only a list of the files without the lines in them, use the -l option. If you want the search to be case insensitive, use the -i option. For example:

grep -rli "header logo" *.php

will list only the PHP files (without the particular lines in them) that contain the expression header logo. All PHP files in the current directory and its subdirectories will be searched, and lower and upper case letters won't be taken into account, so that PHP files will be listed that contain in them expressions such as Header logo, Header Logo, HEADER LOGO, etc.

When you know which particular files contain a word/expression, you can view those files with a text editor like pico or vim, for example, or by using any other method that you prefer (e.g. the file manager of the Pixie control panel).

Was this answer helpful?

 Print this Article

Also Read