Linux - Global Regular Expression Print (GREP command) (line filtering, word search)

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

grep stands for “global regular expression print”.

Grep searches lines of a file that match a regular expression pattern and returns them.

It is by default case sensitive.

Advertising

3 - Output

3.1 - Only Filename

grep -Rl term /directory

searches all files in a directory and outputs only filenames with matched results.

4 - Example

4.1 - Basic

grep -i searchTermRegularExpression my/Path/File/RegularExpressionNameFile

where:

  • searchTermRegularExpression is the search term
  • the option -i turns the search to be case insensitive

4.2 - Regular expression

Same Line                                                       Same Line
                                                              > New Line
Same Line 2                                                     Same Line 2
Different Line                                                | Different Line :)
cat diff.txt | grep '[\>\|]'
                                                              > New Line
Different Line                                                | Different Line :)
Advertising

4.3 - Search within a directory

  • with grep
grep -R SearchPattern  /myPath/ToADir
  • with find
find . -type f -exec grep -l "word"

with Linux, AIX - find command

4.4 - Grep process without the Grep process

  • Standard Ps with Grep:
$ ps -ef | grep nqsserver
oracle    4087  4018  0 13:19 pts/0    00:00:00 grep nqsserver
oracle   23915 20779  0 Mar05 ?        00:06:28 nqsserver -quiet
  • Grep without Grep
$ ps -ef | grep nqsserver | grep -v grep
oracle   23915 20779  0 Mar05 ?        00:06:28 nqsserver -quiet
  • Grep without Grep shortcut (for grep -v)
$ ps -ef | grep [n]qsserver
oracle   23915 20779  0 Mar05 ?        00:06:28 nqsserver -quiet

4.5 - Grep hidden files

Sh - Hidden files

grep pattern .*

Example

grep LD_LIBRARY_PATH .*
.bash_history:echo $LD_LIBRARY_PATH
.bash_profile:  export LD_LIBRARY_PATH=${TT_HOME}/lib:${TT_HOME}/ttoracle_home/instantclient_11_2:${LD_LIBRARY_PATH}
Advertising

4.6 - Or

grep -iE 'first|second'

4.7 - Not

  • Don't show line with jar
cat myFile | grep -v 'jar'
  • With the L option: All ini files *SQL*.ini that doesnot have encrypt=true
grep -r -i -L --include "*.ini" "encrypt=true"  .

5 - Documentation / Reference

lang/bash/grep.txt · Last modified: 2019/06/13 14:54 by gerardnico