grep 命令
grep的来历
global/regular expression/print
g/re/p‘fgrep’ stands for Fixed ‘grep’; ‘egrep’ stands for Extended
‘grep’.
使用正则
使用正则表达式可以极大的方面我们做匹配,正则可以说是各个变成语言必要要支持的技术,grep作为三贱客之一,没有不支持的理由。
使用正则表达式 要用-e 参数指定。
root@kali:~/test# cat a.txt
111
123
456
111
789
root@kali:~/test# grep -E '111|123' a.txt
111
123
111
root@kali:~/test#
更复杂的正则表达式是否支持呢?下面直接上栗子。
root@kali:~/test# echo 123a | egrep -E '\d+a'
root@kali:~/test#
从上图的代码可以看出普通正则表达式并不支持,通过查询info 我们得知 如下规则: 大家可以 使用info grep来查询。
‘[:alnum:]’
Alphanumeric characters: ‘[:alpha:]’ and ‘[:digit:]’; in the ‘C’
locale and ASCII character encoding, this is the same as
‘[0-9A-Za-z]’.‘[:alpha:]’
Alphabetic characters: ‘[:lower:]’ and ‘[:upper:]’; in the ‘C’
locale and ASCII character encoding, this is the same as
‘[A-Za-z]’.‘[:blank:]’
Blank characters: space and tab.‘[:cntrl:]’
Control characters. In ASCII, these characters have octal codes‘[:digit:]’
Digits: ‘0 1 2 3 4 5 6 7 8 9’.‘[:graph:]’
Graphical characters: ‘[:alnum:]’ and ‘[:punct:]’.‘[:lower:]’
Lower-case letters; in the ‘C’ locale and ASCII character encoding,
this is ‘a b c d e f g h i j k l m n o p q r s t u v w x y z’.‘[:print:]’
Printable characters: ‘[:alnum:]’, ‘[:punct:]’, and space.
取反
取反即不满足某个条件。下面直接上代码
root@kali:~/test# cat a.txt
111
123
456
111
789
root@kali:~/test# grep -v 111 a.txt
123
456
789
root@kali:~/test#
递归处理文件
当我们需要茶轴某个文件夹及其子文件夹下的文件里是否有某个文字时应该怎么处理呢? 可以使用find -exec的方式,那有没有更简略的方式呢,愚以为find有点太重。
当然有grep 有这个参数选项。
2. How do I search directories recursively?grep -r 'hello' /home/gigi
使用-r 参数。
下面上find的栗子:
root@kali:~/test# pwd
/root/test
root@kali:~/test# tree
.
├── a.txt
├── b.txt
└── dir_a
├── c.txt
└── m
└── m.txt
2 directories, 4 files
root@kali:~/test# find ./ -print -name "*.txt" -exec grep -n 111 {} \;
./
./dir_a
./dir_a/c.txt
2:111
./dir_a/m
./dir_a/m/m.txt
2:111
./a.txt
1:111
4:111
./b.txt
1:111
4:111
root@kali:~/test#
下面是使用grep的-r选项,有没有很酷?
root@kali:~/test# grep -rn 111
dir_a/c.txt:2:111
dir_a/m/m.txt:2:111
a.txt:1:111
a.txt:4:111
b.txt:1:111
b.txt:4:111
root@kali:~/test#
##默认是当前路径,也可以指定路径
root@kali:~/test# grep -rn 111 ./dir_a
./dir_a/c.txt:2:111
./dir_a/m/m.txt:2:111
root@kali:~/test#
显示行号
使用-n 参数,直接上栗子
root@kali:~/test# cat -n a.txt
1 111
2 123
3 456
4 111
5 789
root@kali:~/test# grep -n 11 a.txt
1:111
4:111
root@kali:~/test#