linux命令之grep


grep命令:打印文件中匹配某个样式的行

格式: grep [options] pattern [filles]

options (选项)

控制样式的选项:

-E : 扩展的grep ,egrep

-f regex-file : 从文件中获取正则表达式 ,fgrep

-i : 不区分大小写

 

#cat argvs.sh 
#!/bin/bash
echo $0 with $# args: "$*"
index=1

for arg in $*
do
	echo Argument ${index} is: ${arg}
	let "index+=1"
done
exit
 grep -i FOR argvs.sh 
for arg in $*

 

-v : 只取不匹配的结果

 

 grep -v -i For argvs.sh 
#!/bin/bash
echo $0 with $# args: "$*"
index=1

do
	echo Argument ${index} is: ${arg}
	let "index+=1"
done
exit

 

控制输出的选项:

-c : 只输出文件中匹配的行数

# grep -c -i For argvs.sh 
1

-l : 只输出内容匹配的文件名

 

grep -l do *.sh 
argvs.sh
ps3_test.sh

 

-L : 与-l相反,输出内容没有匹配的文件名

 

# grep -L for *.sh 
ps3_test.sh

 

-m num : 找到num个匹配行就停止继续查找

 

grep -m 10 '\/etc' all.txt /etc
/etc/securetty
/etc/python2.6
/etc/python2.6/sitecustomize.py
/etc/bash.bashrc
/etc/apparmor
/etc/apparmor/severity.db
/etc/apparmor/subdomain.conf
/etc/apparmor/functions
/etc/apparmor/logprof.conf

 

输出行行首格式选项:

-n : 显示输出行在文件中的行号

-h : 不输出文件名

-H : 输出文件名

 

 grep -H -n -m 10 '\/etc' all.txt 
all.txt:1:/etc
all.txt:2:/etc/securetty
all.txt:3:/etc/python2.6
all.txt:4:/etc/python2.6/sitecustomize.py
all.txt:5:/etc/bash.bashrc
all.txt:6:/etc/apparmor
all.txt:7:/etc/apparmor/severity.db
all.txt:8:/etc/apparmor/subdomain.conf
all.txt:9:/etc/apparmor/functions
all.txt:10:/etc/apparmor/logprof.conf

 

pattern (样式):正则表达式

files (文件名):没有指定文件名默认从标准输入中读取

 

#grep -m 10 -n '^\/etc.*conf$' all.txt 
8:/etc/apparmor/subdomain.conf
10:/etc/apparmor/logprof.conf
14:/etc/laptop-mode/conf.d/auto-hibernate.conf
15:/etc/laptop-mode/conf.d/sched-mc-power-savings.conf
16:/etc/laptop-mode/conf.d/cpufreq.conf
17:/etc/laptop-mode/conf.d/start-stop-programs.conf
18:/etc/laptop-mode/conf.d/hal-polling.conf
19:/etc/laptop-mode/conf.d/configuration-file-control.conf
20:/etc/laptop-mode/conf.d/dpms-standby.conf
21:/etc/laptop-mode/conf.d/usb-autosuspend.conf
# grep -m 10 -n '^\/etc.*conf$' 
/etc .conf
1:/etc .conf
ee
/et aa
/etcdasdaweq/conf
4:/etcdasdaweq/conf


 



相关内容