[Bash] grep command

Zhentiw發表於2024-05-30

grep is a powerful command-line tool used for searching text using patterns. It's widely used for finding specific text within files or output streams.

grep [options] pattern [file...]

Example file

# example.txt
Hello World
This is a sample file
Bash scripting is powerful
Learning grep, awk, and sed
Another line with the word World
$ grep "awk" example.txt

Learning grep, awk, and sed
$ grep -i "AWK" example.txt

Learning grep, awk, and sed

The -i option makes the search case-insensitive.

Search in Multiple Files:

$ grep "awk" example.txt hello.txt

example.txt:Learning grep, awk, and sed

Recursive Search in Directories:

grep -r "search_term" /path/to/directory

The -r option searches recursively through all files in the specified directory.

Display Line Numbers:

$ grep -n "awk" example.txt hello.txt
example.txt:4:Learning grep, awk, and sed

The -n option shows the line numbers of matching lines.

Show Only Matching Part of Line:

$ grep -o awk example.txt

awk

Count Matches:

$ grep -c awk example.txt

1

The -c option counts the number of matching lines.

Invert Match:

$ grep -v awk example.txt

Hello World
This is a sample file
Bash scripting is powerful
Another line with the word World

The -v option selects lines that do not match the pattern.

Use Regular Expressions:

grep -E "^Learning" example.txt

Learning grep, awk, and sed

The -E option allows the use of extended regular expressions.

Try

mkdir -p test_dir
echo "Test file" > test_dir/file1.txt
echo "Another test file" > test_dir/file2.txt
grep -r "test" test_dir

test_dir/file2.txt:Another test file


echo -e "abc123\nabc456\n789" > regex_example.txt
grep -E "[0-9]{3}" regex_example.txt

abc123
abc456
789

echo -e "apple\nbanana\ncherry\napple pie" > regex_example.txt
# Search for lines containing "apple" followed by any character:
grep -E "apple." regex_example.txt

apple pie

Script example

#!/bin/zsh

echo "Enter the search term: "
read search_term

echo "Enter the file name: "
read file_name

if [ -f "$file_name" ]; then
  count=$(grep -c "$search_term" "$file_name")
  echo "The term '$search_term' appears $count times in $file_name."
else
  echo "File $file_name does not exist."
fi

Advance usage

Search for a word and show 2 lines of context before and after each match

grep -C 2 "search_term" filename

Search for Whole Words Only

Search for whole words only (not as part of another word)

grep -w "search_term" filename

相關文章