shell查找某字符串在某文件中出现行数

版权声明:更多内容:http://www.findme.wang ;本文地址: https://blog.csdn.net/hsd2012/article/details/80614544

一、简介

有的时候,我们需要分析日志来排查错误,但是日志文件特别大,打开肯定是很慢的,也是没法接受的,我们需要的是快速定位错误出现的位置,并定向取出错误信息。

快速定位某个字符串在某文件中出现的行数,可以使用 linux中grep命令

默认情况,grep命令只会输出匹配的字符串所在的行,如下:
这里写图片描述
要想同时输出行号,可以指定参数-n,关于-n参数描述如下:

-n, --line-number   print line number with output lines

这里写图片描述
现在,我们已经确定要查询的错误所在行数,就可以通过 tail和head或是sed命令输出特定的行

1、利用tail和head来输出特定的行

通过tail –help ,我们可以看到tail 默认显示最后10行,通过 -n参数可以指定从第n行数开始显示,或是显示最后n行,如下:

-n, --lines=K output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth

也就是说:

tail -n 5 f.txt //显示f.txt最后5行
tail -n +5 f.txt //从第5行开始,显示f.txt

通过head –help ,我们可以看到head默认显示最前10行,通过 -n参数可以指定从倒数第n行开始,显示前面的所有,或是显示最前面的n行

 -n, --lines=[-]K   print the first K lines instead of the first 10; with the leading `-', print all but the last

也就是说:

head -n 5 f.txt //显示f.txt最前面5行
tail -n -5 f.txt //从倒数第5行开始,显示前面的所有内容

比如,在上面我们定位到了8786830行,那么,我们就可以利用tail和head,查其附近的内容(即错误前20行,后10行内容),如下:

tail -n +8786810 err.log |head -n 30

2、利用sed来输出特定的行

通过sed来查看指定的行,就比较简单,格式如下:

sed -n "n1,n2p" f.txt //查看f.txt n1行到n2行之间的内容

比如,在上面我们定位到了8786830行,那么,我们就可以利用sed,查其附近的内容(即错误前20行,后10行内容),如下:

sed -n "8786810,8786840p" err.log

更多内容,可以点击这里:http://www.findme.wang/blog/detail/id/461.html

猜你喜欢

转载自blog.csdn.net/hsd2012/article/details/80614544