1818IP-服务器技术教程,云服务器评测推荐,服务器系统排错处理,环境搭建,攻击防护等

当前位置:首页 - Linux系统 - 正文

君子好学,自强不息!

可能大家还对“linux怎么读取文件的前几行 linux怎么读取文件内容”有些不明白,下面由1818ip小编来为大家解答一下,现在我们来一起看看吧!

本教程操作环境:CentOS 6系统、Dell G3电脑。

在linux中,可用head命令来读取文件的前几行。

head 命令可用于查看文件的开头部分的内容,有一个常用的参数 -n 用于显示行数,默认为 10,即显示 10 行的内容。

读取文件前几行的基本语法格式如下:

head [-n K] 文件名

说明:

  • K 表示行数,该选项用来显示文件前 K 行的内容;

  • 如果使用 “-K” 作为参数,则表示除了文件最后 K 行外,显示剩余的全部内容。

  • 如果省略K,而默认显示 10 行的内容。

head 命令其他两个常用选项及含义
选项 含义
-c K 这里的 K 表示字节数,该选项用来显示文件前 K 个字节的内容;如果使用 “-K”,则表示除了文件最后 K 字节的内容,显示剩余全部内容。
-v 显示文件名;

读取文件的前几行的示例:

指定行数

[root@xuexi ~]# head -n 2 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin

指定末尾除N行不显示外,全部显示

[root@xuexi ~]# head -n -40 /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin

总是显示标题文件名

[root@xuexi ~]# head -n 2 -v /etc/passwd
==> /etc/passwd

指定多个文件

[root@xuexi ~]# head -n 5 /etc/passwd /etc/firewalld/firewalld.conf 
==> /etc/passwd  /etc/firewalld/firewalld.conf

不显示标题文件名

[root@xuexi ~]# head -n 5 -q /etc/passwd /etc/firewalld/firewalld.conf
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin        //此时中间就没有空行
# firewalld config file
 
# default zone
# The default zone used if an empty zone string is used.
# Default: public

注意:head也经常用于管道重定向

以上就是“linux怎么读取文件的前几行 linux怎么读取文件内容”的详细内容,更多请关注1818ip网其它相关文章!

本文来源:1818IP

本文地址:https://www.1818ip.com/post/3902.html

免责声明:本文由用户上传,如有侵权请联系删除!

发表评论

必填

选填

选填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。