How to use the grep command in linux.
Using grep command
grep command search for any particular word or any pattern in any particular Linux file or different files in the same directory.
The search will be regardless to the letters case sensitive so we can find any word even if we dono whether it is upper case or lower case and of course we can search numbers as well.
grep command really comes in handy to filter and display the exact details you want to see in the terminal and also the number of occurrences in the file.
Let’s see the basics on how to use grep command.
Scenario 1:
In a particular directory, need to search a word in a file but not sure about the file name or not sure how files will have that word.
# grep “tomcat” *
(I want to look for the word “tomcat” in the files and using * asterisk to search in all the files in that directory).
Scenario 2:
In a particular directory, need to know the count or occurrence of word in all the files in that directory.
# grep “tomcat” * | wc -l
(w – match the whole word; c – Count of the lines that match a pattern; I – displays list of filenames only).
Scenario 3:
To know how many times a word is repeated or number of occurrences in a specific file.
# grep “tomcat” apache.txt
(apache.txt is a text file).
Scenario 4:
Need to know the count or occurrence of word in a specific file in that directory.
# grep “tomcat” apache.txt | wc -l
Scenario 5:
How to filter a Linux command or Need to know a specific detail in Linux command output.
Example: ipconfig command
# ifconfig ens192
# ifconfig ens192 | grep “inet”
Using advanced grep parameters
Scenario 6:
How to display the word in the files which is under the different sub-directory.
# grep “tomcat” * -R
(R – read all the files in all the sub-directory, recursively).
How to display the word in the files irrespective to the letter case sensitive.
# grep -i “tomcat” *
(I – Ignore case sensitive all the files).
How to exclude a word and display the rest in the files by ignoring case sensitive.
# grep -iv “tomcat” *
(v – don’t include the word “tomcat”).
Redirection using grep parameters
Scenario 7:
How to copy the output to the text file or move the output to the text file.
# grep -i “tomcat” * > tomcat.txt
(We will not get any output in the screen so you can use the cat command to display the data inside the text file).
# cat tomcat.txt
Scenario 8:
How to sort the displayed data by name.
# grep -i “tomcat” webservers.txt | sort -k 2
# grep -i “tomcat” webservers.txt | sort -rk 3
(k sort by column name and number is col2 and col 3 and r sort by reverse-descending order).
Comments
Post a Comment