shell入門系列(9)grep

  • 2019 年 10 月 4 日
  • 筆記

shell入門系列(9)grep

簡介

搜索文本文件內容,默認輸入匹配到的那一行

  • 通配符
  • 正則表達式

入門小案例

搜索單個文件

# grep "內容" 文件  grep "bash" ~/.bashrc  grep bash ~/.bashrc

搜索多個文件

#  grep "bash" ~/.bashrc ~/.oneinstack

選項

-E

使用正則表達式

#  grep -E "[0-9]+" ~/.bashrc  egrep "[0-9]+" ~/.bashrc

[外鏈圖片轉存失敗(img-Us3HVPA2-1563242272153)(http://ww1.sinaimg.cn/large/006jIRTegy1fzde5ckqulg30ig0abweg.gif)]

-v

排除內容。

#  grep -v "bash" ~/.bashrc

-c

顯示搜索行數

#  grep -c "bash" ~/.bashrc

-o

輸出匹配到的內容

#  grep -o "bash" ~/.bashrc 

通過管道 傳給 wc 計算行數

#  grep -o "bash" ~/.bashrc | wc -l

-n

帶行號顯示

#  grep -n "bash" ~/.bashrc

-l

輸出匹配到內容的源,這裡我們用的源是文件。

#  grep -l "bash" ~/.bashrc ./test1.txt ./test2.txt ./test3.txt

下面給出測試文件內容!

test1.txt

bash 我是第一行  lll  kkk lll kkk  kkk

test2.txt

我是第一行  nice work world  keyborad black  red

test3.txt

bash kkk lll kkk  kkl ddk llkd 

-L

與 -l 相反 ,輸出沒有匹配到的源

#  grep -L "bash" ~/.bashrc ./test1.txt ./test2.txt ./test3.txt

-R 遞歸搜索

-R 可以遞歸某一個目錄下的文件,搜索其每一個文件的內容。

#  grep -R -n "main" /usr/include

-i 不分大小寫

#  grep -i "main" ~/.bashrc

-e 多重搜索

#  grep -e "bash" -e "m" ~/.bashrc -n

--include 指定文件類型

#  grep "bash" /usr/include -R -n --include "*.c"  grep "bash" /usr/include -R -n --include "*.{c,cpp,h}"

--exclude 排除文件類型

#  grep "bash" /usr/include -R -n --exclude "*.c"

-q 安靜模式

-q 不會顯示任何東西,但是可以通過輸出 命令結果查看

# 如果echo 輸出為0 則搜到了, 如果不等於0 則沒有搜到  grep -q "bash" ~/.bashrc  echo $?

最好使用腳本模式進行這個操作

q.sh

#! /bin/bash  if [ $# -eq 2 ];  then  	echo "$0  match_text filename"  	exit  fi  match_text=$1  filename=$2    grep -q $match_text $filename    if [ $? -eq 0 ];  then  	echo "exit"  else  	echo "does not exit"  fi

-A 向後匹配

把匹配到的後幾行都顯示出來

#  grep "bash" ~/.bashrc -A 3

-B 向前匹配

把匹配到的前幾行都顯示出來

#  grep "bash" ~/.bashrc -B 3

-C 同時向前向後匹配

把匹配到的後幾行和前幾行都顯示出來

#  grep "bash" ~/.bashrc -C 3

-Z 消除間隔

# 以 0 分隔  grep "bash" /usr/include/*.c -LZ  grep "bash" /usr/include/*.c -LZ | xags -0 rm
Exit mobile version