Linux/Unix:Cat命令显示行号
时间:2020-01-09 10:37:33 来源:igfitidea点击:
在Linux或Unix之类的操作系统下,如何使用cat命令显示名为myapp.c的文件的行号?您可以使用cat命令连接文件并在Linux或Unix等操作系统下显示在屏幕上。
cat命令还使用以下语法对从第一行开始的所有输出行进行编号:
语法
语法为:
cat -n fileNameHere
或者
cat --number foo.c
或在屏幕上无法显示文本时,使用more命令/less命令作为过滤器:
cat --number foo.c | more
或者
cat --number foo.c | less
-b/--number-nonblank选项编号所有非空输出行,从1开始,语法为:
cat -b fileNameHere
或者
cat --number--nonblank filename
最后,通过-s/--squeeze-blank选项抑制或删除重复的空输出行:
cat -s -n fileNameHere cat -s -n /etc/resolv.conf
输出示例:
1 #
2 # Mac OS X Notice
3 #
4 # This file is not used by the host name and address resolution
5 # or the DNS query routing mechanisms used by most processes on
6 # this Mac OS X system.
7 #
8 # This file is automatically generated.
9 #
10 search theitroad.com
11 nameserver 8.8.8.8
12 nameserver 192.168.2.254
13 nameserver 8.8.4.4
或(仅GNU语法)
cat --squeeze-blank -n filename
nl命令
在Linux或Unix oses下使用文件的nl命令数字行。
语法为:
nl filename
例子
创建一个名为hello.c的文本文件,如下所示:
/* Purpose: Sample see program to print Hello world on stdout
* Author: theitroad
* Copyright: None / Copyleft
*/
#include<stdio.h>
/* our main */
int main(void){
printf("Hello world\n");
return 0;
}
使用cat或nl命令显示行号:
cat -n hello.c nl hello.c
输出示例:
使用cat and nl命令显示hello.c的行号。
关于sed的注意事项
要仅打印第三行,请使用sed命令:
sed -n 3p /etc/resolv.conf
要仅打印第三行和第五行,请使用sed命令:
sed -n -e 3p -e 5p /etc/resolv.conf
要查看特定范围,请说出显示3到5之间的行,请运行:
sed -n 3,5p /etc/resolv.conf
有关更多信息,请参见手册页sed(1)。

