linux grep用法小白梳理(1)

来源:互联网 发布:sql删除嵌套select 编辑:程序博客网 时间:2024/06/13 02:44

grep 用法梳理

grep命令是linux中用于文本搜索的神奇工具,现梳理如下

1.搜索包含指定字符的文本行

grep example filename #会输出所有包含example字符的文本行

或者

grep "example" filename #会输出所有包含example字符的文本行

2.也可以从 stdin中读取

echo -e "this is a word\n next line"|grep word

this is a word

3.可同时对多个文件进行搜索

grep "match_txt" file1 file2 file3

4.用--coler 选项可以标红输出匹配的字符

grep word filename --color=auto

this is the line containingword

5.当然grep也可以使用正则表达式来匹配指定字符,不过需要添加-E选项,此选项意味着使用扩展正则表达式,或者也可以默认使用默认允许正则表达式的grep命令 egrep,例如

grep -E "[a-z]+" filename  等于 egrep "[a-z]+" filename

6.只输出文件中匹配到的文本部分,可以使用-o选项

echo -e "this is word\n next line." |egrep -o "[a-z]+\." --color=auto
line.

7.-o选项是输出匹配到的,对应的一个选项是-v,过滤掉匹配掉的(将匹配结果进行反转),例如

echo -e "this is word\n next line." |egrep -v "[a-z]+\."
this is word

8.统计文件或文本中包含匹配字符串的行数,不过这个只是统计匹配的行数,并不是匹配的次数

grep -c "test" filename

9.如果就想输出匹配的次数其实也是可以做到的,我们可以这么做

echo -e "1 2 3 4\nhello\n5 6" | egrep -o "[0-9]"|wc -l

10.打印出包含匹配字符的行号:

grep next -n test.txt

或者可以这样

cat test.txt |grep next -n

如果涉及多个文件,他会随着输出结果打印出文件名


0 0
原创粉丝点击