1
---
Finding a File Containing a Particular Text String In Linux ServerThe Linux syntax to find string in files is as follows:
grep "text string to search" directory-path
grep [option] "text string to search" directory-path
grep -r "text string to search" /directory-path
grep -r -H "text string to search" directory-path
grep -E -R "word-1|word-2" /path/to/directory
# Find string in files on Linux #
grep -E -w -R "word-1|word-2" directory-path
find all files containing specific text on Linux?
The syntax is:
$ grep -E 'pattern' -rnw /path/to/dir/
$ grep -E 'word1|word2' -rnw /home/vivek/backups/
just display the filename use the cut command as follows:
# grep -H -R arif /etc/postfix/*
# grep -H -R arif /etc/* | cut -d: -f1
Let us see some common example on how to use grep to search for strings in files.
How to search and find all files for a given text string
In this example, search for a string called ‘redeem reward’ in all text (*.txt) files located in /home/tom/ directory, use:
$ grep "redeem reward" /home/tom/*.txt
Let us find text called “redeem reward” in files under Linux:
$ grep "redeem reward" ~/*.txt
Task: Search all subdirectories recursively to find text in files
You can search for a text string all files under each directory, recursively with -r option:
$ grep -r "redeem reward" /home/tom/
OR
$ grep -R "redeem reward" /home/tom/
Look for all files containing cacheRoot text on Linux:
$ grep -R cacheRoot /home/vivek/
Trying to find all files containing specific text on my Linux desktop
I want to search the whole Linux server for a string. In other words, use the following command to search for a word called “barfoo”:
$ sudo grep -R "barfoo" /
The / indicate root file system. The above command may take a lot of time. Hence, it is better to restrict the search to particular directory as per your needs:
$ sudo grep -R "barfoo" /etc/
Task: Only display filenames
By default, the grep command prints the matching lines. You can pass -H option to print the filename for each match:
$ grep -H -r "redeem reward" /home/tom
Sample outputs:
filename.txt: redeem reward
foobar.txt: redeem reward
...
To just display the filename use the cut command as follows:
$ grep -H -R vivek /etc/* | cut -d: -f1
Sample outputs:
filename.txt
foobar.txt
...
Task: Suppress file names
The grep command shows output on a separate line, and it is preceded by the name of the file in which it was found in the case of multiple files. You can pass the -h option to suppress inclusion of the file names in the output:
$ grep -h -R 'main()' ~/projects/*.c
Task: Display only words
You can select only those lines containing matches that form whole words using the -w option. In this example, search for word ‘getMyData()’ only in ~/projects/ dirctory:
$ grep -w -R 'getMyData()' ~/projects/
Task: Search for two or more words
Use the egrep command as follows:
$ grep -E -w -R 'word1|word2' ~/projects/
Task: Hide warning spam
grep command generate error message as follows due to permission and other issues:
No such file or directory
No such device or address
Permission denied
To hide all errors or warning message spam generated by the grep command, append 2>/dev/null to grep command. This will send and hide unwanted output to /dev/null device:
$ grep -w -R 'getMyData()' ~/projects/ 2>/dev/null
Task: Display matched text in color
Pass the --color option to the grep command display matched text/words in color on the terminal:
grep --color 'word' file
grep --color -R 'word' /path/to/dir
grep --color -R "192.168.1.5" /etc/
grep --color -R -h "192.168.1.5" /etc/
grep --color -R -h "192.168.1.5" /etc/ 2>/dev/null
Sample outputs:
Fig.01: grep command in action with colors and hiding the warnings on screen
Task: Ignore case
Our final example ignore case distinctions in both the search PATTERN and the input files:
$ grep -i -R 'word' /path/to/dir
$ grep -i -r 'income tax' ~/accounting/
Summing up
You learned how to search and find a file containing a particular text string (words) under Linux using the grep command.
Finding text strings within files using grep
In this example search for lines starting with any lowercase or uppercase letter:
$ grep "^[a-zA-Z]" -rns ~/projects/texts/
Where,
-r – Recursive search
-R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option
-n – Display line number of each matched line
-s – Suppress error messages about nonexistent or unreadable files
-w – Only work on words i.e. search only those lines containing matches that form whole words
-l – Show the name of each input file when match found
-i – Ignore case while searching
Read the following manual pages using the man command or grep command:
$ man grep
$ grep --help
Find Files in Linux Using the Command Line
find command to search for files and directories based on their permissions, type, date, ownership, size, and more. It can also be used in combination with other tools such as grep or sed.
Linux find Command Syntax
The general syntax for the find command is as follows:
find [options] [path...] [expression]
Copy
The options attribute controls the treatment of the symbolic links, debugging options, and optimization method.
The path... attribute defines the starting directory or directories where find will search the files.
The expression attribute is made up of options, search patterns, and actions separated by operators.
To search for files in a directory, the user invoking the find command needs to have read permissions on that directory.
Let’s take a look at the following example:
find -L /var/www -name "*.js"
Copy
The option -L (options) tells the find command to follow symbolic links.
The /var/www (path…) specifies the directory that will be searched.
The (expression) -name "*.js tells find to search files ending with .js (JavaScript files).
Find Files by NameFinding files by name is probably the most common use of the find command. To find a file by its name use, the -name option followed the name of the file you are searching for.
For example, to search for a file named document.pdf in the /home/linuxize directory you would use the following command:
find /home/linuxize -type f -name document.pdf
Copy
To run a case-insensitive search, change the -name option with -iname:
find /home/linuxize -type f -iname document.pdf
Copy
The command above will match “Document.pdf”, “DOCUMENT.pdf” ..etc.
Find Files by ExtensionSearching for files by extension is the same as searching for files by name. For example, to find all files ending with .log.gz inside the /var/log/nginx directory you can use:
find /var/log/nginx -type f -name '*.log.gz'
Copy
It is important to mention that when you use the wildcard character, you must either quote the pattern or escape the asterisk * symbol with backslash \ so that it doesn’t get interpreted by the shell.
To find all files that don’t match the regex *.log.gz you can use the -not option. For example, to find all files that don’t end in *.log.gz you would use:
find /var/log/nginx -type f -not -name '*.log.gz'
Copy
Find Files by Type
Sometimes you might need to search for specific file types such as normal files, directories or symlinks. In Linux, everything is a file.
To search for files based on their type, use the -type option and one the following descriptors to specify the file type:
f: a regular file
d: directory
c: character devices
b: block devices
p: named pipe (FIFO)
s: socket
For instance, to find all directories in the current working directory, you would use:
find . -type d
Copy
The common example would be to recursively change the website file permissions to 644 and directory permissions to 755 using the chmod command:
find /var/www/my_website -type d -exec chmod 0755 {} \;
find /var/www/my_website -type f -exec chmod 0644 {} \;
Copy
Find Files by Size
To find files based on the file size, pass the -size parameter along with the size criteria. You can use the following suffixes to specify the file size:
b: 512-byte blocks (default)
c: bytes
w: two-byte words
k: Kilobytes
M: Megabytes
G: Gigabytes
The following command will find all files of exactly 1024 bytes inside the /tmp directory:
find /tmp -type f -size 1024c
Copy
The find command also allows you to search for files that are greater or less than a specified size.
In the following example, we are searching for all files less than 1MB inside the current working directory. Notice the minus - symbol before the size value:
find . -type f -size -1M
Copy
If you want to search for files with size greater than 1MB, then you need to use the plus + symbol:
find . -type f -size +1M
Copy
You can even search for files within a size range. The following command will find all files between 1 and 2MB:
find . -type f -size +1M -size 21M
Copy
Find Files by Modification Date
The find command can also search for files based on their last modification, access, or change time.
Same as when searching by size, use the plus and minus symbols for “greater than” or “less than”.
Let’s say that a few days ago, you modified one of the dovecot configuration files, but you forgot which one. You can easily filter all files under the /etc/dovecot/conf.d directory that ends with .conf and have been modified in the last five days with:
find /etc/dovecot/conf.d -name "*.conf" -mtime 5
Copy
Here is another example of filtering files based on the modification date using the -daystart option. The command below will list all files in the /home directory that were modified 30 or more days ago:
find /home -mtime +30 -daystart
Copy
The -perm option allows you to search for files based on the file permissions.
For example, to find all files with permissions of exactly 775 inside the /var/www/html directory, you would use:
find /var/www/html -perm 644
Copy
You can prefix the numeric mode with minus - or slash /.
When slash / is used as the prefix, then at least one category (user, group or others) must have at least the respective bits set for a file to match.
Consider the following example command:
find . -perm /444
Copy
The above command will match all the files with read permissions set for either user, group or others.
If minus - is used as the prefix then for the file to match at least the specified bits must be set. The following command will search for files that have read and write permission for the owner and group and are readable by other users:
find . -perm -664
Copy
To find files owned by a particular user or group, use the -user and -group options.
For example, to search for all files and directories owned by the user linuxize, you would run:
find / -user linuxize
Copy
Here is a real-world example. Let’s say you want to find all files owned by the user www-data and change the ownership of the matched files from www-data to nginx:
find / -user www-data -type f -exec chown nginx {} \;
Copy
Find and Delete Files
To delete all matching files, append the -delete option to the end of the match expression.
Make sure you are using this option only when you are confident that the result matches the files that you want to delete. It is always a good idea to print the matched files before using the -delete option.
For example to delete all files ending with .temp from the /var/log/ you would use:
find /var/log/ -name `*.temp` -delete
---