1. grep
grep 是全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它能使用正则表达式搜索文本,并把匹配的行打印出来。
用法:
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] [-e PATTERN | -f FILE] [FILE...]
首先使用ls命令和输出重定向生成两个用来测试grep命令的文本
root@CGS-21-14:/home/lhp# ls /usr/ > ls_usr.txt
root@CGS-21-14:/home/lhp# ls /etc/ > ls_etc.txt
1). 在ls_usr.txt中搜索含有“bin”的字符串
root@CGS-21-14:/home/lhp# grep bin ls_usr.txt
bin
sbin
2). 从多文件中搜索含有”bin”的字符串
root@CGS-21-14:/home/lhp# grep bin *
ls_etc.txt:bindresvport.blacklist
ls_usr.txt:bin
ls_usr.txt:sbin
root@CGS-21-14:/home/lhp# grep bin ls*
ls_etc.txt:bindresvport.blacklist
ls_usr.txt:bin
ls_usr.txt:sbin
3). 从ls_usr.txt中搜索含“bin”和”BIN”的字符串。
root@CGS-21-14:/home/lhp# echo /BINs >> ls_usr.txt
root@CGS-21-14:/home/lhp# echo /BINABLE >> ls_usr.txt
root@CGS-21-14:/home/lhp# echo /Bining >> ls_usr.txt
root@CGS-21-14:/home/lhp# grep -i bin ls_usr.txt
bin
sbin
/BINs
/BINABLE
/Bining
4). 在ls_usr.txt中搜索以this开头case结尾的字符串
root@CGS-21-14:/home/lhp# echo "this is test case" >> ls_usr.txt
root@CGS-21-14:/home/lhp# grep -i "this.*case" ls_usr.txt
this is test case
5). 在ls_usr.txt中搜索整词is,不像1)中那种含部分,并加上不区分大小写
root@CGS-21-14:/home/lhp# grep -iw "is" ls_usr.txt
this is test case
6). 显示ls_etc.txt中含emacs匹配行前、后、前后 4行