grep命令

grep命令在文本中搜索指定的内容。

grep命令的常用选项

  • -c 只输出匹配行的计数。
  • -i 不区分大小写(只适用于单字符)。
  • -h 查询多文件时不显示文件名。
  • -l 查询多文件时只输出包含匹配字符的文件名。
  • -n 显示匹配行及行号。
  • -s 不显示不存在或无匹配文本的错误信息。
  • -v 显示不包含匹配文本的所有行。

搜索内容

[root@vmax0105 test_shell]# grep "abc" file
abc
abc123
123abc

-n 显示行号

[root@vmax0105 test_shell]# grep -n "abc" file
1:abc
2:abc123
3:123abc

-w 精准匹配

[root@vmax0105 test_shell]# grep -w "abc" file
abc

-v 显示不包含指定内容的行

[root@vmax0105 test_shell]# grep -v "abc" file
123

-c 显示匹配到的内容的行数

[root@vmax0105 test_shell]# grep -c "abc" file
3

-E 使用扩展正则表达式(grep命令默认使用基础正则表达式)

[root@vmax0105 test_shell]# grep -E "[a-z]{3}" file
abc
abc123
123abc
[root@vmax0105 test_shell]# egrep "[a-z]{3}" file
abc
abc123
123abc
 
-o 只输出匹配到的文本
[root@vmax0105 test_shell]# egrep -o "[a-z]{3}" file
abc
abc
abc
 
统计文件中匹配项的数量
[root@vmax0105 test_shell]# grep "abc" file | wc -l
3
 
-l 列出匹配模式所在的文件。和-l效果相反的选项是-L,它会返回一个不匹配的文件列表。 
[root@vmax0105 test_shell]# grep -l abc file file2
file
[root@vmax0105 test_shell]# grep -l 123 file file2
file
file2
 
-i 忽略模式中的大小写
[root@vmax0105 test_shell]# grep "abc" file
abc
abc123
123abc
[root@vmax0105 test_shell]# grep -i "abc" file
ABC
abc
abc123
123abc
 
-e 使用grep匹配多个模式
[root@vmax0105 test_shell]# grep -e "abc" -e "123" file
abc
123
abc123
123abc
-R 在多级目录中对文本进行递归搜索
[root@vmax0105 test_shell]# grep "^abc" /tmp/ -R -n
grep: /tmp/.s.PGSQL.5832: 没有那个设备或地址
/tmp/test_shell/file:1:abc
/tmp/test_shell/file:3:abc123
grep: /tmp/SERVERENGINE_SOCKETMANAGER_2019-08-26T11:38:25Z_4380: 没有那个设备或地址
grep: /tmp/.ICE-unix/20837: 没有那个设备或地址
grep: /tmp/.X11-unix/X0: 没有那个设备或地址

遇到的问题:错误信息也显示出来了,影响查看

解决方法:把错误信息重定向到指定文件中

[root@vmax0105 test_shell]# grep "^abc" /tmp/ -R -n 2> file.out
/tmp/test_shell/file:1:abc
/tmp/test_shell/file:3:abc123

 grep 的静默输出

有时候,我们并不打算查看匹配的字符串,而只是想知道是否能够成功匹配。这可以通过设置 grep 的静默选项( -q )来实现。在静默模式中, grep 命令不会输出任何内容。它仅是运行命令,然后根据命令执行成功与否返回退出状态。0表示匹配成功,非0表示匹配失败。

#! /bin/bash
# 文件名:test.sh
# 用途:测试文件是否包含指定内容

function content_exit(){
    # 如果传入函数的参数的个数不为2,则退出当前函数
    if [ $# -ne 2 ];then
        echo "参数个数不匹配"
        exit 1
    fi

    match_text=$1
    filename=$2
    grep -q "$match_text" $filename

    if [ $? -eq 0 ];then
        echo "该文件包含指定内容"
    else
        echo "该文件不包含指定内容"
    fi
}

function main(){
    content_exit abc file
}
main
 
 
 
原文地址:https://www.cnblogs.com/lfjn/p/11420662.html