Grep
Grep
bash : grep
Pulkit Singh
A270150424001
05/07/2025
INTRODUCTION
• A command-line tool to search for specific patterns in files or streams.
• The grep command lets the user find text in a given file or out-put quickly and
easily.
• By giving grep a string to search for, it will print out only lines that contain that
string and can print the corresponding line numbers for that text.
• The “simple” use of the command is well-known, but there are a variety of more
advanced uses that make grep a powerful search tool.
• grep is actually a combination of four different tools, each with its unique style of
finding text: basic regular expressions, extended regular expressions, fixed strings,
and Perl-style regular expression.
2
05/07/2025
• Example:
3
05/07/2025
4
05/07/2025
Input :
Output :
5
05/07/2025
6
05/07/2025
Or
7
05/07/2025
8
05/07/2025
9
05/07/2025
10
05/07/2025
11
05/07/2025
o Output
12
05/07/2025
Case problem
• Q1. Display lines containing 'to' from the 'testfile3.txt' input file.
o Solution:
13
05/07/2025
Case problem
• Q2. Display only the first two matching lines containing 'he' form 'testfile2.txt'
input file.
o Solution
• Q3. Display the first 5 matching lines that do not conatin 'on' from 'testfile.txt'
input file.
o Solution
14
05/07/2025
Case problem
• Q4. Display lines from 'testfile.txt' that contain 'is' along with line number prefix.
o Solution
• Q5. For the input file sample.txt, display lines containing amigo prefixed by the
input filename as well as the line number.
15
05/07/2025
Case problem
• Q6. Count the total number of lines containing banana in the input files
sample.txt and code.txt.
• Solution
• Q7. For the input file `testfile2.txt`, match all lines that start with 'cat` or end with
`sun`.
o Solution
16
05/07/2025
Case problem
• Q8. For the input file `testfile3.txt`, match all lines containing `on` but not as a
whole word.
o Solution
• Q9. Count the total number of times the whole words `removed` or `rested` or
`received` or `replied` or `refused` or `retired` are present in the `patterns.txt`
file.
o Solution
17