grep使用

来源:互联网 发布:js分割网址为数组 编辑:程序博客网 时间:2024/05/02 23:25

1 、标识查找对象 grep --color=auto   


2、只打印匹配的文本  grep -o

lsn@android:~$ cat grep.test-rw-rw-r-- 1 lsn lsn 0 8月  10 22:54 2016_03_01.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:36 2016_03_21.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:54 2016_03_22.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:11 2016_03_25.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:55 2016_03_30.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:46 2016_03_31.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:12 2016_04_01.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:55 2016_04_18.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:12 2016_04_22.loglsn@android:~$ grep -o 2016_03_01 grep.test 2016_03_01

3、反向匹配    grep -v

lsn@android:~$ grep -v 2016_03 grep.test -rw-rw-r-- 1 lsn lsn 0 8月  10 23:12 2016_04_01.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:55 2016_04_18.log-rw-rw-r-- 1 lsn lsn 0 8月  10 23:12 2016_04_22.log


4、正则匹配,grep -E 或 egrep,一般都用alias设置好


5、统计匹配的行数,不是匹配的次数  grep -c

lsn@android:~$ grep -c 3 grep.test 8lsn@android:~$ grep -o 3 grep.test | wc -l14


6、查找匹配字符在该行的那个位移  grep -b -o

lsn@android:~$ echo "hello world" | grep -b -o "world"6:world


7、返回匹配文本的文件列表  grep -l  反向列表 grep -L


8、忽略大小写 grep -i


9、递归查找  grep -R -n

递归查找只包含特定文件  grep "test" . -R -n --include *.(cf,txt)

递归查找不包含特定文件  grep "test" . -R -n --exclude "FILE"

递归查找不包含特定目录 --exclude-dir


10、静默输出 grep -q,如果匹配输出0,如果不匹配返回非0

#!/bin/bash#test grep -qif [ $# -ne 2 ];thenecho "$0 match_text filename"exitfimatch_test=$1filename=$2grep -q $match_test $filenameif [ $? -ne 0 ]thenecho "The text exists in the file"elseecho "The text does not exist in the file"fi


11、输出前后行数

grep -A n  输出匹配行和之后n行

grep -B n  输出匹配行和之前n行

grep -C n 输出匹配行和前后n行


12、匹配多个样式  grep -e  或者使用 grep -f 调用文件

lsn@android:~$ grep -e 2016_03_01.log -e 2016_04_18.log grep.test -rw-rw-r-- 1 lsn lsn 0 8月  10 22:54 2016_03_01.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:55 2016_04_18.log

lsn@android:~$ cat file 2016_03_01.log2016_04_18.loglsn@android:~$ lsn@android:~$ grep -f file grep.test -rw-rw-r-- 1 lsn lsn 0 8月  10 22:54 2016_03_01.log-rw-rw-r-- 1 lsn lsn 0 8月  10 22:55 2016_04_18.log



0 0