Linux 基礎之文本搜索工具grep

一、grep (縮寫來自Globally search a Regular Expression and Print)是一種強大的文本搜索工具,它能使用正則表達式搜索文本,並把匹配的行打印出來。Unix的grep家族包括grep、egrep和fgrep

 grep: 默認支持基本正則表達式;
egrep: 擴展正則表達式;
fgrep: 不支持正則表達式元字符,搜索字符串的速度快

二、通過man手冊獲取grep幫助信息:

#man grep

GREP(1)                                                                GREP(1)

NAME
       grep, egrep, fgrep - print lines matching a pattern

SYNOPSIS
       grep [options] PATTERN [FILE...]
       grep [options] [-e PATTERN | -f FILE] [FILE...]

DESCRIPTION
       Grep  searches  the  named input FILEs (or standard input if no files are named, or the file name - is given) for
       lines containing a match to the given PATTERN.  By default, grep prints the matching lines.

       In addition, two variant programs egrep and fgrep are available.  Egrep is the same as  grep -E.   Fgrep  is  the
       same as grep -F.

三、grep的常用選項

--color=auto
        export GREP_COLOR='01;36'
    -v: 反向選取,只顯示不符合模式的行;
    -o: 只顯示被模式匹配到的字串,而不是整個行;
    -i: 不區分字符大小寫;
    -A #:顯示匹配到的行時,順帶顯示其後面的#個行;
        -A 2
    -B #:前面的#行;
    -C #:前後的#行;

    -E: 使用擴展的正則表達式
        grep -E = egrep

三、grep正則表達式基本元字符集

元字符:不表示字符本身的意義,而用於額外功能性的描述

^:錨定行首的符合條件的內容

# grep "^root" /etc/passwd //搜索以root開頭的行

image
$: 錨定行尾的符合條件的內容

#grep “bash$” /etc/passwd //搜索以bash結尾的行

image

.: 匹配任意單個字符

image

匹配s和l之間有單個任意字符的內容

image


*:匹配緊挨在其前面的字符任意次(包含0次)

image

匹配k前面有0個或任意個s

image

[]:匹配指定範圍內的任意單個字符

匹配D或d中間包含兩個任意字符並以n結尾的行

image
[^]:匹配指定範圍外的任意單個字符

image

#grep "[^A-Z].*a" text --color=auto  //匹配任意一個非大與字母后面面跟0個或多個任意字符以a結尾的行

image
\?: 匹配緊挨在其前面的字符0次或1次;

匹配b之前有0個或1個a

image

匹配a和b之前有0個或1個任意字符

image

\{m,n\}: 匹配其前面的字符至少m次,至多n次;
            \{0,n\}: 至多n次;0-n次;
            \{m,\}:至少m次
            \{m\}: 精確匹配m次;

匹配b 前面的a 至少1次至多2次

image

\<: 錨定詞首,用法格式:\<pattern
            \b: \bpattern

搜索以root爲詞首的行

image

        \>: 錨定詞尾,用法格式:pattern\>
            \b: pattern\b

搜索以root爲詞尾的行

image
           \<pattern\>:錨定單詞

搜索包含root單詞的行

image

\(\): 分組,用法格式: \(pattern\)

\1  :可以引用第一個分組匹配到的內容
\2  :可以引用第二個分組匹配到的內容


搜索R或r和d之間出現兩個任意字符而後又跟0個或多個任意字符 ,並在其後引用匹配到的內容

image

字符集合

[:digit:] 所有數字 0-9       

[:lower:] 所有小寫字母  a-z

[:upper:] 所有大寫字母 A-Z

[:punct:] 所有標點符號

[:space:] 表示空格或tab鍵

[:alpha:] 表示所有字母(包含大小寫)a-zA-Z

[:alnum:] 表示所有字母和數字  a-zA-Z0-9

注:非需要這樣表示[^[] ], 如[[:space :]]表示空格 [^[:space:]] 表示非空

 

搜索/boot/grub/grub.conf 以空格開頭的行

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章