SEARCH IN SHELL SCRIPT MADE EASY

Nkugwa Mark William
2 min readFeb 13, 2023

--

Searching for a File in Linux Shell Scripting

In shell scripting, there are several ways to search for a file within a system. Some of the common commands used for this are find, locate, and which.

The find command is used to search for files and directories within a specific directory and its subdirectories. The basic syntax for the find command is as follows:

find <start_dir> <expression>

Where start_dir is the directory where the search will begin, and expression is the condition for the search. For example, to search for a file called example.txt in the current directory and its subdirectories, the following command can be used:

find . -name example.txt

The locate command, on the other hand, is used to search for files based on their names. It uses a database of file names and paths, so it is faster than find. The basic syntax for the locate command is as follows:

locate <file_name>

For example, to search for a file called example.txt, the following command can be used:

locate example.txt

The which command is used to search for the executable file of a given command. The basic syntax for the which command is as follows:

which <command_name>

For example, to find the location of the ls command, the following command can be used:

which ls

Searching Within Files in Linux Shell Scripting

To search for specific text within files, the grep command is commonly used in shell scripting. The basic syntax for the grep command is as follows:

grep "<text_to_search>" <file_name>

For example, to search for the word "example" in the file example.txt, the following command can be used:

grep "example" example.txt

The grep command can also be used to search for text within multiple files by specifying a directory instead of a single file. The basic syntax for this is as follows:

grep "<text_to_search>" <directory_name>

For example, to search for the word “example” in all the files within the current directory, the following command can be used:

grep "example" .

It is important to note that the grep command is case-sensitive, so the word "example" and "Example" will be considered as two different words. To make the search case-insensitive, the -i option can be used. For example:

grep -i "example" example.txt

--

--

Nkugwa Mark William
Nkugwa Mark William

Written by Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites

No responses yet