shell入门系列(9)grep

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值