­

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