Searching Files with grep

grep prints lines from files which match a pattern
For example, to find an entry in the password file /etc/passwd relating to the user ‘nancy’:
$ grep nancy /etc/passwd
 grep has a few useful options:

  • -i stands for upper/lower case (optional in your case)
  • -r searches through files in specified directories, recursively
  • -l prints just the names of files which contain matching lines( stands for "show the file name, not the result itself`.)
  • -c prints the count of matches in each file
  • -n numbers the matching lines in the output
  • -v reverses the test, printing lines which don’t match
  • R stands for recursive.
Patter Matching
Use grep to fid patters, as we as simple strings
 Patters are expressed as reguar expressios
grep -Ril "text-to-find-here" /
 Certain punctuation characters have special meaning
 For example this might be a better way to search for acy’s etry i the password fie:
$ grep ’ˆacy’ /etc/passwd
 The caret (ˆ) achors the patter to the start of the ie
 I the same way, $ acts as a achor whe it appears at the ed of a strig, makig the
patter match oy at the ed of a ie
44
iux System Administration Module 7. Search Text Fies Using Regular Expressions
Matching Repeated Patters
 Some regexp specia characters are aso specia to the she, ad so eed to be protected with
Quotes or backsashes
 We ca match a repeatig patter by addig a modifier:
$ grep -i ’cotiued\.*’
 Dot (.) o its own would match ay character, so to match an actua dot we escape it with \
 The * modifier matches the precedig character zero or more times
 Simiary, the \+ modifier matches oe or more times
Matchig Aterative Patters
 Mutipe subpatters ca be provided as ateratives, separated with \|, for example:
$ grep ’fish\|chips\|pies’ food.txt
 The previous commad fids ies which match at east oe of the words
 Use \(...\) to eforce precedence:
$ grep -i ’\(cream\|fish\|birthday\) cakes’ deicacies.txt
 Use square brackets to buid a character cass:
$ grep’ [Jj]oe [Bb]oggs’ staff.txt
 Any singe character from the class matches; ad rages of characters ca be expressed as
a-z

Comments

Popular Posts

Install and configure rsyslog Centralized logging server in CentOS

How to fix postfix/smtp Network is unreachable error

Could not join realm: Necessary packages are not installed: sssd-tools sssd libnss-sss libpam-sss adcli