Display lines containing a pattern from a file using “grep”

To display lines which contains “pattern” from a file. Use grep command as

grep pattern file_name

Use -v option to display lines that does not contain pattern

Eg:-
Here I want to include lines containing “testa/N1_SNR” pattern, but exclude lines containing “testa/N1_SNR-” pattern and concatenate with content of other file.

I use below code

{ grep "testa/N1_SNR" all_hcopy.scp | grep -v "SNR-" ; cat CleanTR08_hcopy.scp ; } > only_testa_N1.scp

Use { cmd1; cmd2; } to execute all commands in the current shell
see http://mywiki.wooledge.org/BashSheet#Command_Lists

Grep recursively, but only certain file extensions

Use the below code
grep -r --include="file_pattern" "Pattern_To_search" Directory_Path
For example:
To search all the files with extension “.m”, and find lines in these files containing the word gmm
grep --include="*.m" -nRHIi "gmm" .

Note: Here the options specified are
-r or -R for recursive search
-n Prefix each line of output with the line number within its input file.
-H Print the filename for each match
-I Process a binary file as if it did not contain matching data; this is equivalent to the –binary-files=without-match option
-i for case insensitive search

 

See more usages of grep command at using-grep-regular-expressions-to-search-for-text-patterns-in-linux

Leave a comment