In this post, I will use the Linux command line to search files on the directory and search text within files. You need a basic understanding of Linux to go ahead. If you missed the first part READ from here.
Create directory and files
Next, we will create a temp directory and a few dummy files on which we search. Let’s create a directory naming temp and move inside the directory
Now create a bunch of files.
The command generates 10 different files with a .txt extension. Now we need to edit a few files and enter text for our search operation. We can use nano or vim to edit files. I am going to use vim here-
Now the ground is ready. Let’s play with searching now. We use a command called find
or we can search file by name or extension
Now we have a problem. This command is case sensitive. So the search is ignoring file.File5.txt . To solve the issue use i before -name; like this-
Some other useful find method commands are-
To make a powerful search result, we can always combine commands.-
There is another method to search within the file. It is called grep. grep requires two parameters. The first one is the search text and the second one is a filename.
These commands will show if the search text found or not. We also can print the list of files where search key exists-
Recursive search has one drawback. It always required a wildcard to do a recursive search. But this is Linux. And every problem has a workaround. So you can use a combination of different command.
But exec has risk too. It may cause unavoidable security problems, so it is recommended to use execdir instead of exec