Linux脚本攻略学习笔记之head、tail详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/whandgdh/article/details/85044070

一、head

1.1、打印前10行

语法:
$ head file #默认打印前10行

  seq 20 | head  #可见head也可以从stdin中读取数据

在这里插入图片描述

1.2、指定打印前几行

head -n 4 file

1.3、打印除了最后M行之外所有的行

head -n -M file # -M 表示一个负数,并非选项

seq  11 | head -n -5
打印除了最后5行外

在这里插入图片描述

二、tail

2.1 打印文件最后10行

与head一样 默认打印10行,只是打印文件最后10行
语法:$ tail file

2.2、可以用下面的代码从 stdin 中读取输入

$ cat text | tail

2.3、打印最后5行

$ tail -n 5 file

2.4、打印除了前M行之外所有的行

语法 :tail -n +(M+1) file

打印除前5行之外的所有行, M+1=6 ,因此使用下列命令:

  seq 11 | tail -n +6
 打印 除了前面5行,

在这里插入图片描述

2.5 -f

tail 有一个特殊的选项 -f 或
–follow ,它们会使 tail 密切关注文件中新添加的内容,并随着数据的增加持续保持更新:
语法 $ tail -f growing_file

用vim 编辑file.txt 文件如下
在这里插入图片描述

再登录另外一个xshell
PID= ( p i d o f v i m ) t a i l f s t u d y / t a i l / f i l e . t x t p i d = (pidof vim) tail -f study/tail/file.txt --pid= PID
在这里插入图片描述
看到打印并没有结束
再回到file.txt编辑的xshell上保存file.txt,并退出vim
回到tail的xshell上看到 打印结束
在这里插入图片描述
这就是tail 一个很有意思的特性:当某个给定进程结束之后, tail 也会随之终结

猜你喜欢

转载自blog.csdn.net/whandgdh/article/details/85044070