常用Linux命令:head/tail

常用Linux命令:head/tail

今天看一个日志,这日志有点长,有个几万行,但是我只需要其中的[x, y]行之间的一个消息Sample,如何去取呢?

假设我们需要取出一个文件中的[x, y]行之间的内容,可以:

head -n y filename | tail -n +x

注:vi的行标是从1开始的,而不是从0开始的!

如果我要取第7行到第12行(闭区间)内的数据,使用以下命令即可:

[7, 12]

head -n 12 info.txt | tail -n +7

OK,下面简单说下head以及tail.

现在我有文件info.txt,其内容为:

[jiang@eb50 ~]$ cat info.txt 
this is line1
this is line2
this is line3
this is line4
this is line5
this is line6
this is line7
this is line8
this is line9
this is line10
this is line11
this is line12
this is line13
this is line14
this is line15
this is line16
this is line17
this is line18
this is line19
this is line20
this is line21
this is line22
this is line23
this is line24
this is line25
this is line26
this is line27
this is line28
this is line29
this is line30

head

列出一个文件的前x行。

1.

[jiang@eb50 ~]$ head info.txt
this is line1
this is line2
this is line3
this is line4
this is line5
this is line6
this is line7
this is line8
this is line9
this is line10

啥都不加默认显示前10行。

[1, 10]

2.

[jiang@eb50 ~]$ head -n 6 info.txt 
this is line1
this is line2
this is line3
this is line4
this is line5
this is line6

使用-n指定前x行。

[1, x]

3.

[jiang@eb50 ~]$ head -n -24 info.txt
this is line1
this is line2
this is line3
this is line4
this is line5
this is line6

-n后面的衔接一个负数x,代表不输出后面的(-x)行。

比如这里x是-24,那么就不输出后面的(-(-24))=24行。

总共有30行,不输出后24行,于是只输出前6行。


tail

列出一个文件的后x行。

1.

[jiang@eb50 ~]$ tail info.txt 
this is line21
this is line22
this is line23
this is line24
this is line25
this is line26
this is line27
this is line28
this is line29
this is line30

什么都不加默认输出最后的10行。

2.

[jiang@eb50 ~]$ tail -n 5 info.txt 
this is line26
this is line27
this is line28
this is line29
this is line30

类似head,只是这里显示的是末尾x行。

3.

[jiang@eb50 ~]$ tail -n +26 info.txt 
this is line26
this is line27
this is line28
this is line29
this is line30

从第x行开始直到文件结束。

注意这里是加号,区别于head的减号。

回到一开始的话题:

如何取出一个文件中[m, n]行的内容呢?

本文开头已经介绍了一种,先去头head,再取尾tail,能不能先取尾巴tail,然后再取头head呢?

(当然可以,大家可以试下~)

再思考一个问题:

如何取从m行开始的h行数据?

[m, m+h-1]

方法一:

15行开始的三行数据:

[jiang@eb50 ~]$ head -n 17 info.txt| tail -n +15
this is line15
this is line16
this is line17

m=15,m+h-1=15+3-1=17.

方法二:

[jiang@eb50 ~]$ tail -n +15 info.txt | head -n 3
this is line15
this is line16
this is line17

其实没啥区别,就是先用tail还是先用head的区别。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值