linux常用的读取文件内容指令

时间:2022-07-23
本文章向大家介绍linux常用的读取文件内容指令,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

linux常用于读取文件内容指令主要有以下七种: cat,tac,nl,more,less,head,tail

cat 文件名 –将文件内容显示在屏幕上 cat -n 文件名 –将文件内容显示在屏幕上,并显示行号 cat -b 文件名 –将文件内容显示在屏幕上,并显示行号,但是不显示空白行行号

tac则是和cat反过来的(名字都是反过来的) tac 文件名 –将文件内容显示在屏幕上,但是是从最后一行开始往前显示 tac -s separator 文件名 –从separator往后倒序输出,倒序输出不包含separator,输出到最后一行再按照顺序将separator之前的内容输出 tac -b -s separator 文件名 –从separator往后倒序输出,倒序输出包含separator,输出到最后一行再按照顺序将separator之前的内容输出

创建文件readfile.txt,在文件中输入内容

[root@localhost tmp]# cat readfile.txt 
one
two three
four five six
seven eghit nine ten
[root@localhost tmp]# tac readfile.txt 
seven eghit nine ten
four five six
two three
One

tac和cat显示的顺序是相反的

[root@localhost tmp]# tac -s "six" readfile.txt 

seven eghit nine ten
one
two three
four five six
[root@localhost tmp]# tac -b -s "six" readfile.txt 
six
seven eghit nine ten
one
two three
four five 

nl 文件名 (就是nl -b t 文件名) 使用nl指令肯定是显示行号的,主要是操作行号如何显示 nl -b a 文件名 –显示行号,空行也显示行号 nl -b t 文件名 –显示行号,空行不显示行号(默认值) nl -w 数字x 文件名 –行号字段所占用的位数 nl -n ln 文件名 –行号在字段最前方那段空间最左端显示 nl -n rn 文件名 –行号在字段最前方那段空间最右端端显示,且不加0 nl -n rz 文件名 –行号在字段最前方那段空间最右端端显示,且加0 行号占四位

[root@localhost tmp]# nl -w 4 readfile.txt 
   1    one
   2    two three
   3    four five six
   4    seven eghit nine ten

行号前自动补全0

[root@localhost tmp]# nl -n rz -w 4 readfile.txt 
0001    one
0002    two three
0003    four five six
0004    seven eghit nine ten

行号在最左端显示

[root@localhost tmp]# nl -n ln -w 4 readfile.txt 
1       one
2       two three
3       four five six
4       seven eghit nine ten

可以执行翻页操作的读取文件内容指令 more 文件名 空格:向下翻页 Enter:向下换一行 /字符串: 查找文件内容 q: 离开more,不再显示内容 b: 往回翻页

less 文件名 空格:向下翻页 Pageup: 向上翻页 Pagedown: 向下翻页 /字符串: 向下搜索 ?字符串: 向上搜索 n: 重复前一个搜索 N: 反向重复前一个搜索 q: 离开less

haed 文件名 –显示文件头十行 head -n x 文件名 –显示文件头x行,如果x为负数,则显示除最后x行外的前面所有行

tail文件名 –显示文件头十行 tail -n x 文件名 –显示文件头x行,如果x前面有+号,则显示除前面x-1行外的所有行

如果想要看第十一行到第二十行,可以结合管道流来实现 两种方式 先获取头二十行,再获取最后十行

[root@localhost tmp]# head -n 20 man_db.conf | tail -n 10
# --------------------------------------------------------
# MANDATORY_MANPATH         manpath_element
# MANPATH_MAP       path_element    manpath_element
# MANDB_MAP     global_manpath  [relative_catpath]
#---------------------------------------------------------
# every automatically generated MANPATH includes these fields
#
#MANDATORY_MANPATH          /usr/src/pvm3/man
#
MANDATORY_MANPATH           /usr/man

先获取除头十行外的所有行,再获取头十行

[root@localhost tmp]# tail -n +11 man_db.conf | head -n 10
# --------------------------------------------------------
# MANDATORY_MANPATH         manpath_element
# MANPATH_MAP       path_element    manpath_element
# MANDB_MAP     global_manpath  [relative_catpath]
#---------------------------------------------------------
# every automatically generated MANPATH includes these fields
#
#MANDATORY_MANPATH          /usr/src/pvm3/man
#
MANDATORY_MANPATH           /usr/man