0
0
Bash Scriptingscripting~5 mins

Basic regex in grep in Bash Scripting

Choose your learning style9 modes available
Introduction
You use grep with basic regex to find text patterns in files or outputs quickly and easily.
You want to find all lines containing a specific word in a file.
You need to search for lines starting with a certain letter or word.
You want to find lines that end with a specific character or word.
You want to find lines containing either one word or another.
You want to search for simple patterns like digits or letters in text.
Syntax
Bash Scripting
grep 'pattern' filename
The pattern is a basic regular expression (regex) that describes what you want to find.
Single quotes around the pattern prevent the shell from changing special characters.
Examples
Finds lines containing the exact word 'cat' anywhere in the file.
Bash Scripting
grep 'cat' file.txt
Finds lines that start with 'Hello'. The ^ means start of line.
Bash Scripting
grep '^Hello' file.txt
Finds lines that end with 'end'. The $ means end of line.
Bash Scripting
grep 'end$' file.txt
Finds lines containing 'cat' or 'dog'. The \| means OR in basic regex.
Bash Scripting
grep 'cat\|dog' file.txt
Sample Program
This script creates a file with some words and sentences. Then it uses grep with basic regex to find lines starting with 'cat', lines ending with 'og', and lines containing either 'cat' or 'dog'.
Bash Scripting
# Create a sample file
cat << EOF > sample.txt
cat
caterpillar
dog
catalog
end
Hello world
Hello there
EOF

# Find lines starting with 'cat'
grep '^cat' sample.txt

# Find lines ending with 'og'
grep 'og$' sample.txt

# Find lines containing 'cat' or 'dog'
grep 'cat\|dog' sample.txt
OutputSuccess
Important Notes
In basic regex for grep, the OR operator is written as \| and needs to be escaped.
Use ^ to match the start of a line and $ to match the end of a line.
Always quote your pattern to avoid shell interpreting special characters.
Summary
grep with basic regex helps you find text patterns in files easily.
Use ^ and $ to match start and end of lines.
Use \| for OR conditions in basic regex.