跳至內容

Shell 程式設計/正則表示式

來自華夏公益教科書,自由的教科書

正則表示式通常用於透過像 findgrep 這樣的外部程式來操作字串。

正則表示式中常用的字元

[編輯 | 編輯原始碼]
  ^ Anchor to beginning of line
  $ Anchor to end of line
  . Any single character
  [ ] Encloses pattern matching characters


匹配字元

[編輯 | 編輯原始碼]
  [:alnum:] Alphanumeric characters
  [:alpha:] Letters
  [:ascii:] ASCII characters
  [:blank:] Space or tab
  [:cntrl:] ASCII control characters
  [:digit:] Digits
  [:graph:] Noncontrol, nonspace characters
  [:lower:] Lowercase letters
  [:print:] Printable characters
  [:punct:] Punctuation characters
  [:space:] Whitespace characters, including vertical tab
  [:upper:] Uppercase letters
  [:xdigit:] Hexadecimal digits

擴充套件 grep 模式

[編輯 | 編輯原始碼]

可以使用 -E 模式在 grep 中使用以下以 '\' 開頭的字元。

  ? Match is optional but may be matched at most once
  "*" Must be matched zero or more times (without "")
  + Must be matched one or more times
  {n} Must be matched n times
  {n, } Must be matched n or more times
  {n,m} Must be matched between n and m times

正則表示式的使用示例

[編輯 | 編輯原始碼]
  • 在檔案 example_text_file 中查詢以 'e' 結尾的文字
   grep e$ example_text_file
  • 查詢
  Crazy Monkey
  Crazy Donkey
  Cranky Money

在 another_text_file 中

   grep -E Cra..\*[[:space:]][[:print:]]o... another_text_file

上面的命令告訴 grep 使用擴充套件模式,查詢 "Cra",後面跟著任意數量的字串,後面跟著空格,後面跟著可列印字元,後面跟著 "o",後面跟著三個字元,並在 another_text_file 中搜索它。

華夏公益教科書