linux shell grep 判断,Linux | grep用于if逻辑判断

本文探讨了grep命令的-q和-w/e参数在编程逻辑中的高效使用,如grep-q用于快速检查文件内容并决定if语句的执行结果,grep-w进行精确单词匹配,grep-e则用于搜索包含特定字符的文件。通过实例演示,展示了这些参数如何简化代码并提高效率。
摘要由CSDN通过智能技术生成

突然发现grep -q 用于if 逻辑判断很好用。

-q参数:本意是 Quiet; do not write anything to standard output.  Exit immediately with zero status if any match is found, even if an error was detected.   中文意思为,安静模式,不打印任何标准输出。如果有匹配的内容则立即返回状态值0。

————————————————————————

-w参数:Does a word search.

grep -w用于字符串精确匹配

若文件中的内容包括如下:

262 a3

262

26

如果 grep ‘26’ file,结果是三行全部都被显示

若要精确匹配26所在行

使用grep -w ‘26’ file

————————————————————————

-e参数:显示文件中符合条件的字符

查找当前目录下所有文件中包含字符串”Linux”的文件,会将含有Linux字符串的所有文件匹配出来。

1、小应用

# cat a.txt

nihao

nihaooo

hello

# if  grep -q hello a.txt ; then echo yes;else echo no; fi

yes

# if grep -q word a.txt; then echo yes; else echo no; fi

no

2、把文档转换成一行,并且通过判断查找里面的word

# cat a.txt | xargs > b.txt

# if grep –q ni b.txt; then echo yes; else echo no; fi

yes

# if grep –qw ni b.txt; then echo yes; else echo no; fi

no

# if grep –qw nihao b.txt; then echo yes; else echo no; fi

yes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值