How to Search and Filter Lines Containing Specific Strings in Linux Text Files


2 views

The most straightforward way to find lines containing a specific string in a Linux file is using the grep command:

grep "my string" file_name

This will output all lines containing the exact phrase "my string" in file_name.

To perform a case-insensitive search (matching "My String", "MY STRING", etc.):

grep -i "my string" file_name

The -i flag makes the search ignore case differences.

To show line numbers along with matching lines:

grep -n "my string" file_name

Example output:

42:This line contains my string
87:Another example with my string

You can combine these options for powerful searches:

grep -in "my string" file_name

This performs a case-insensitive search while displaying line numbers.

For more complex pattern matching using regular expressions:

grep -E "[Mm]y [Ss]tring" file_name

Or to match lines starting with "my string":

grep "^my string" file_name

To simply count how many lines contain the string:

grep -c "my string" file_name

You can search across multiple files:

grep "my string" *.txt

Or recursively through directories:

grep -r "my string" /path/to/directory

To find lines that don't contain the string:

grep -v "my string" file_name

While grep is most common, other tools can also do the job:

Using awk:

awk '/my string/ {print}' file_name

With line numbers:

awk '/my string/ {print NR, $0}' file_name

Using sed:

sed -n '/my string/p' file_name



The grep command is the standard tool for searching text patterns in Linux files. The basic syntax is:

grep "search_pattern" filename

For example, to search for "error" in log.txt:

grep "error" /var/log/syslog

By default, grep searches are case-sensitive. For case-insensitive search:

grep -i "my string" file_name

To force case-sensitive search (explicitly):

grep -s "MyString" file_name

Add the -n flag to show line numbers:

grep -n "critical" server.log

Sample output:

42:2023-01-15 12:30:45 [CRITICAL] System overload
87:2023-01-15 14:15:22 [CRITICAL] Disk full

For regular expression patterns:

grep -E "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}" emails.txt

To search multiple files recursively:

grep -r "function_name" /path/to/source/code/
  • -w - Match whole words only
  • -v - Invert match (show non-matching lines)
  • -c - Count of matching lines
  • -A num - Show num lines after match
  • -B num - Show num lines before match
  • -C num - Show num lines around match

Example combining multiple options:

grep -inw "timeout" --include=*.conf /etc/