Grep: Difference between revisions
From DikapediaV2
(Created page with "<B>grep</B> - Pretty much a search function. Prints lines matching a pattern. ----- Examples: cat [file] | grep "word" # Prints any line with "word" grep -i # Ignore case senisitivity *i is for INSENSITIVE* grep -irl [word] [dir] # Ignore case distinctions, Read all files under each directory, recursively, Suppress normal output; grep [word] [in file/dir] # Searches up "word" in that file or dir g...") |
No edit summary |
||
Line 47: | Line 47: | ||
grep -o 'needle' file | wc -l | grep -o 'needle' file | wc -l | ||
====Search for a string and show the following lines before/after it==== | |||
---- | |||
you can use -B num to set how many lines before the match and -A num for the number of lines after the match. | |||
grep -B 3 -A 2 foo README.txt |
Latest revision as of 13:57, 4 October 2024
grep - Pretty much a search function. Prints lines matching a pattern.
Examples:
cat [file] | grep "word" # Prints any line with "word" grep -i # Ignore case senisitivity *i is for INSENSITIVE* grep -irl [word] [dir] # Ignore case distinctions, Read all files under each directory, recursively, Suppress normal output; grep [word] [in file/dir] # Searches up "word" in that file or dir grep [x$] [file] # Searches the file with any word that ENDS "x" in it. Variation: [xxx$] multiple letter search that ends with these letters. grep [^x] # Searches the file with any word that STARTS with "x" grep [^x$] # Searches lines that ONLY has 'x' in it. grep "x.*" [file] # Searches up a letter, doesn't matter if it is in the beginnging or end of the line. grep -i "^l.*rse$" [file] # Searches file for anything starts with "l", anything in the middle, and ends in "rse" grep -i '[ab]' [file] # Searches all lines that have a 'a' or 'b' in it. grep [Xx]avier # Searches lines that contain [X]avier or [x]avier grep [wrd] [file] | grep "word" grepception. grep -v '^x' [file] # '-v' means inverse, so this means, search all lines that DO NOT start with 'x' grep '[^brackets]' # Search all lines with anything THAT IS NOT IN THE BRACKETS grep --color=always # use color to highlight
Search for two words at once
grep -E 'word1|word2' *.doc
Count the number of occurrences
grep's -o will only output the matches, ignoring lines; wc can count them:
grep -o 'needle' file | wc -l
Search for a string and show the following lines before/after it
you can use -B num to set how many lines before the match and -A num for the number of lines after the match.
grep -B 3 -A 2 foo README.txt