cmd line tutorials - gencmd

cmd line tutorials - gencmd

The grep Command

Unix-Linux Mac

The grep command is a powerful text search utility that can be used to search for and display lines of text that match a specified pattern.

The name grep comes from the words “global regular expression print.” It can be used to search for patterns in a variety of different file types - text, binary, and compressed files.

Syntax

The basic syntax for the grep command is as follows:

grep [options] pattern file1 file2 ...

The pattern argument is the regular expression that you want to search for. The file1 and file2 arguments are the files that you want to search. You can also use the - symbol to represent standard input, which is the input that is typed into the terminal window.

Examples

Display all lines in the file “myfile.txt” that contain the word “foo”:

grep foo myfile.txt

Display all lines in txt files in the current directory that contain the word “bar”:

grep bar *.txt

Display all lines in the current directory that contain a phone number.

grep -E "[0-9]{3}-[0-9]{3}-[0-9]{4}" *.txt

Options

The grep command has a number of options that can be used to modify its behavior. Some of the most common options are:

-i: Ignore case.

-E: Enable extended regular expressions.

-v: Invert the match, so that the output only contains lines that do not match the pattern.

-n: Print the line number of each matching line.

-c: Only print a count of the number of matching lines.

For more information on the grep command and its options, please see the man page: man grep.

Additional Tips

You can use the -r option to recursively search all of the subdirectories in the current directory.

You can use the -w option to only match whole words.

You can use the -e option to specify multiple patterns to search for.

With gencmd

grep, like find is a powerful command with the right options. Figuring out and remembering the options, though, is tough. gencmd can be particularly useful with grep.

gencmd -c grep find files containaing hello in all folders

  • grep -r hello .