1. 程式人生 > >linux命令系列 grep

linux命令系列 grep

grep, egrep, fgrep - print lines matching a pattern

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

 

linux系統中grep命令是一種強大的文字搜尋工具,它能使用正則表示式搜尋文字,並把匹配的行打印出來,grep全稱是Global Regular Expression Print

1. 常用選項:

  -E, --extended-regexp: Interpret PATTERN as an extended regular expression.   # 開啟擴充套件(Extend)的正則表示式

  -i, --ignore-case: Ignore case distinctions in both the PATTERN and the input files.   # 忽略大小寫

  -v, --invert-match: Invert the sense of matching, to select non-matching lines.  # 反過來,只打印沒有匹配的,而匹配的反而不列印

       -n, --line-number: Prefix each line of output with the 1-based line number within its input file.  # 顯示行號

  -w, --word-regexp  # 被匹配的文字只能是單詞,而不能是單詞中的某一部分,如文字中有liker,而我搜尋的只是like,就可以使用-w選項來避免匹配liker

    Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word

    constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the
    underscore.

  -c, --count: Suppress normal output; instead print a count of matching lines for each input file.  # 顯示總共有多少行被匹配到了,而不是顯示被匹配到的內容,注意如果同時使用-cv選項是顯示有多少行沒有被匹配到。

  -o, --only-matching: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.  # 只顯示被模式匹配到的字串。

  -A NUM, --after-context=NUM: Print NUM lines of trailing context after matching lines.   # 顯示匹配到的字串所在的行及其後NUM行

  -B NUM, --before-context=NUM: Print NUM lines of leading context before matching lines.  # 顯示匹配到的字串所在的行及其前NUM行

  -C NUM, -NUM, --context=NUM: Print NUM lines of output context.  # 顯示匹配到的字串所在的行及其前後各NUM行

2. 模式部分:

  基本正則表示式

    匹配字元

      .  : 任意一個字元

      [abc] : 表示匹配[abc]中任意一個字元

      [a-zA-Z] : 匹配a-z或A-Z之間任意一個字元

      [^123] : 匹配123之外的任意一個字元