Pattern Searching
GREP stands for Global Regular Expression Print / Pattern. It helps us to find the pattern through different ways.
a)Currently I am in /home/ubuntu. Consider there is a file testing.txt inside ubuntu directory. I am adding the content We are learning devops under testing.txt file
Apple
Mango
Banana
Orange
Pineapple
Grapes
We are learning devops
Now we can run the command
ubuntu@ip-172-31-25-118:~$ grep devops testing.txt
Syntax: grep <keyword-name> <filename/directoryname>
Output: We are learning devops
Now if we change the devops character to DevOps then it won't print the output because grep will search only for pattern.
ubuntu@ip-172-31-25-118:~$ grep DevOps testing.txt
For this, we need to use -i flag. It search for pattern on the basis of Case Insensitive.
ubuntu@ip-172-31-25-118:~$ grep -i DevOps testing.txt
Output: We are learning devops
Note:- If there is a directory and if you search any content inside that directory then you can run below command.
grep -r devops folder1/
-> Here '-r' stands for recursive which recursively search the subdirectories and file inside parent directory.
I have created a content "How are you" inside grep.txt file
root@ip-172-31-25-118:/home/ubuntu/A# vim grep.txt
Now I am at the home directory.
root@ip-172-31-25-118:~# grep -r are /home/ubuntu/A
Output: /home/ubuntu/A/grep.txt: how are you?
Eg: You can fetch the user from /etc/passwd file
ubuntu@ip-172-31-25-118:~$ cat /etc/passwd | grep daya
Using pipe symbol (|) you can take the output of one command and share that output as a input to second command.
Output: daya:x:1002:1003::/home/daya:/bin/sh
Also you can copy these output in some file using Redirection (>)
Eg: ubuntu@ip-172-31-25-118:~$ cat /etc/passwd | grep daya > tester.txt
ubuntu@ip-172-31-25-118:~$ cat tester.txt
Output: daya:x:1002:1003::/home/daya:/bin/sh
Eg: It find the specific word.
ubuntu@ip-172-31-25-118:~$ lsblk | grep -w loop
Output:
loop0 7:0 0 25.2M 1 loop /snap/amazon-ssm-agent/7993
loop1 7:1 0 55.7M 1 loop /snap/core18/2829
loop2 7:2 0 38.8M 1 loop /snap/snapd/21759
Subscribe to my newsletter
Read articles from Bilal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by