飞翔灬吾爱的Blog
Linux | grep用于if逻辑判断
2019-6-20 fishyoung

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