1. 程式人生 > 實用技巧 >Linux 字元處理之【grep】

Linux 字元處理之【grep】

引數:

  • -i: 不區分大小寫
  • -c: 統計包含匹配的行數
  • -n: 輸出行號
  • -v: 反向匹配

示例檔案: (example.txt)

The cat's name is Tom, what's the mouse's name?
The mouse's NAME is Jerry
They are good friends

1、找出包含name的行

# 等價於 cat example.txt | grep 'name'
grep 'name' example.txt # 輸出
The cat's name is Tom, what's the mouse's name?

預設grep搜尋是區分大小寫的,所以搜尋name時只搜尋到name所在的第一行,第二行大寫的NAMW沒有匹配到。

2、忽略搜尋內容大小寫

# 等價於 cat example.txt | grep -i 'name'
grep -i 'name' example.txt # 輸出
The cat's name is Tom, what's the mouse's name?
The mouse's NAME is Jerry

3、統計搜尋內容行數

# 等價於 cat example.txt | grep -c 'name'
grep -c 'name' example.txt # 輸出
1
# 等價於 cat example.txt | grep -ci 'name'
grep -ci 'name' example.txt # 輸出
2

4、搜尋除指定字元所在行的其他內容

# 等價於 cat example.txt | grep -v 'name'
grep -v 'name' example.txt # 輸出
The mouse's NAME is Jerry
They are good friends