linux(十六)文件和目录相关命令-查看文件头部内容head与查看文件尾部内容tail

54 阅读3分钟

接下来,我们来看一下查看文件头部内容命令head与查看文件尾部命令tail

 

这两个命令使用比较简单,看一下就好。

 

一:查看文件头部内容命令head

1:命令格式

head (参数) 文件名

 

2:参数说明

-q 隐藏文件名

-v 显示文件名

-c<数目> 显示的字节数。

-n<行数> 显示的行数。

 

3:测试一下

(1):查看test.sh文件内容

root@iZijvdp1z0m5q4Z:~# head test.sh
test write
total 252
drwx------ 13 root root  4096 Aug 22 17:40 ./
drwxr-xr-x 23 root root  4096 Aug 11 15:25 ../
-rw-r--r--  1 root root 39333 May 31 15:59 1.tar.gz
drwxr-xr-x  2 root root  4096 Apr 15 16:46 .antiword/
-rw-r--r--  1 root root     9 Aug 11 15:28 a.txt
-rw-------  1 root root 63620 Aug 11 17:23 .bash_history
-rw-r--r--  1 root root  3106 Apr  9  2018 .bashrc
drwxr-xr-x  2 root root  4096 Apr 15 16:46 bin/

 

从上边我们可以发现,head默认读取文件中前10行的内容

 

(2):查看test.sh文件前3行的内容

root@iZijvdp1z0m5q4Z:~# head -n 3  test.sh
test write
total 252
drwx------ 13 root root  4096 Aug 22 17:40 ./

 

比较实用的参数就这两个,剩下的有兴趣自己测试一下。

 

二:查看文件尾部命令tail

1:命令格式

tail(参数) 文件名

 

2:参数说明

-f 循环读取

-q 不显示处理信息

-v 显示详细的处理信息

-c<数目> 显示的字节数

-n<行数> 显示文件的尾部 n 行内容

 

-f循环读取这个参数还是很有意思的,下面详细说一下。

 

3:测试一下

(1):读取test.sh尾部数据

root@iZijvdp1z0m5q4Z:~# tail test.sh
drwxr-xr-x  2 root root  4096 Jul 15  2020 .rpmdb/
-rw-r--r--  1 root root    66 Jul 15  2020 .selected_editor
drwx------  2 root root  4096 Mar  9  2021 .ssh/
drwxr-xr-x  3 root root  4096 Jul  6  2020 .subversion/
-rw-r--r--  1 root root    11 Aug 22 17:37 test.sh
drwxr-xr-x  2 root root  4096 Dec 21  2020 .vim/
-rw-------  1 root root 11952 Aug 22 17:40 .viminfo
-rw-r--r--  1 root root   343 Jul  1 13:59 .wget-hsts
-rw-------  1 root root   305 Aug 22 15:31 .Xauthority
test write

 

从上边我们可以看出,tail和head是一样的,都是默认读取10行。

 

(2):读取test.sh尾部3行

root@iZijvdp1z0m5q4Z:~# tail -n 3 test.sh
-rw-r--r--  1 root root   343 Jul  1 13:59 .wget-hsts
-rw-------  1 root root   305 Aug 22 15:31 .Xauthority
test write

 

(3):监控test.sh文件写入的变化

这个就比较有意思了,一般我们使用这个命令来监控日志的变化。

我们来测试一下。开两个终端:

首先我们先监控一下test.sh

tail -f test.sh

在开一个新的终端,向test.sh追加写入内容

echo "追加写入的内容" >> test.sh

具体效果如下图所示:

1234.gif

 

以上大概就是head与tail命令的基本使用方法。

 

有好的建议,请在下方输入你的评论。