CentOS 7 打印某个配置文件内容并带行号
在 CentOS 7 系统的命令行中,打印某个配置文件的内容,并且带上行号。
创建测试配置文件
第一步,使用echo test-info-{001..9} | xargs -n1命令,打印输出 9 行测试内容。
[root@centos7 ~]# echo test-info-{001..9} | xargs -n1test-info-001test-info-002test-info-003test-info-004test-info-005test-info-006test-info-007test-info-008test-info-009[root@centos7 ~]#
第二步,将测试内容写入文件。
[root@centos7 ~]# echo test-info-{001..9} | xargs -n1 > /root/test.conf[root@centos7 ~]# cat /root/test.conftest-info-001test-info-002test-info-003test-info-004test-info-005test-info-006test-info-007test-info-008test-info-009[root@centos7 ~]#
方法 1 :使用 cat 命令
[root@centos7 ~]# cat -n /root/test.conf1 test-info-0012 test-info-0023 test-info-0034 test-info-0045 test-info-0056 test-info-0067 test-info-0078 test-info-0089 test-info-009[root@centos7 ~]#
其中-n参数表示,对所有输出的行,从 1 开始进行编号。
方法 2 :使用 vi 或 vim 命令
[root@centos7 ~]# vim /root/test.conf1 test-info-0012 test-info-0023 test-info-0034 test-info-0045 test-info-0056 test-info-0067 test-info-0078 test-info-0089 test-info-009:set nu
输入:set nu命令并回车,表示显示行号。输入:set nonu命令并回车,表示取消显示行号。
方法 3 :使用 grep 命令
使用grep命令,查找test.conf文件内容。
[root@centos7 ~]# grep -n "test" /root/test.conf1:test-info-0012:test-info-0023:test-info-0034:test-info-0045:test-info-0056:test-info-0067:test-info-0078:test-info-0089:test-info-009[root@centos7 ~]#
其中-n参数表示,在查找到的内容前面加行号。
或者,把"test"参数改为".",双引号里面表示一个正则表达式,点号表示任意字符。也就是查找了文件里的全部字符。

方法 4 :使用 awk 命令
[root@centos7 ~]# awk '{print NR,$0}' /root/test.conf1 test-info-0012 test-info-0023 test-info-0034 test-info-0045 test-info-0056 test-info-0067 test-info-0078 test-info-0089 test-info-009[root@centos7 ~]#
其中NR参数表示,显示行号。
方法 5 :使用 sed 命令
[root@centos7 ~]# sed '=' /root/test.conf | xargs -n21 test-info-0012 test-info-0023 test-info-0034 test-info-0045 test-info-0056 test-info-0067 test-info-0078 test-info-0089 test-info-009[root@centos7 ~]#
其中'='参数表示,显示行号。使用xargs -n2命令表示,每一行显示两列。
(完)