Linux | grep用于if逻辑判断

  • 内容
  • 相关

突然发现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

 您阅读这篇文章共花了:

上一篇:Linux | shell里if 判断条件正则表达式=~中引号问题

下一篇:Linux | 防火墙什么场景下需要配置黑洞路由

本文标签:    

版权声明:本文依据CC-BY-NC-SA 3.0协议发布,若无特殊注明,本文皆为《fishyoung》原创,转载请保留文章出处。

本文链接:Linux | grep用于if逻辑判断 - http://www.fishyoung.com/post-255.html