Shell脚本将文件编号
时间:2020-01-09 10:42:10 来源:igfitidea点击:
问题描述:如何给文本文件的每一行编号?
如何编写Shell脚本以显示添加了行号的文本文件?
解决方法:您不必编写Shell脚本即可将数字添加到文本文件或者代码示例中。
您可以使用nl命令将每个文件添加到屏幕上,并添加行号。
nl命令示例
执行命令,如下所示:
$ nl /etc/passwd
输出示例:
1 root:x:0:0:root:/root:/bin/bash
2 daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3 bin:x:2:2:bin:/bin:/bin/sh
4 sys:x:3:3:sys:/dev:/bin/sh
5 sync:x:4:65534:sync:/bin:/bin/sync
6 games:x:5:60:games:/usr/games:/bin/sh
7 man:x:6:12:man:/var/cache/man:/bin/sh
8 lp:x:7:7:lp:/var/spool/lpd:/bin/sh
9 mail:x:8:8:mail:/var/mail:/bin/sh
10 news:x:9:9:news:/var/spool/news:/bin/sh
......
...
40 quagga:x:119:126:Quagga routing suite,,,:/var/run/quagga/:/bin/false
41 oracle:x:1004:1004::/usr/lib/oracle/xe:/bin/bash
42 telnetd:x:112:120::/nonexistent:/bin/false
nl命令还有更多选择:
$ nl --help
输出:
Usage: nl [OPTION]... [FILE]...
Write each FILE to standard output, with line numbers added.
With no FILE, or when FILE is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-b, --body-numbering=STYLE use STYLE for numbering body lines
-d, --section-delimiter=CC use CC for separating logical pages
-f, --footer-numbering=STYLE use STYLE for numbering footer lines
-h, --header-numbering=STYLE use STYLE for numbering header lines
-i, --page-increment=NUMBER line number increment at each line
-l, --join-blank-lines=NUMBER group of NUMBER empty lines counted as one
-n, --number-format=FORMAT insert line numbers according to FORMAT
-p, --no-renumber do not reset line numbers at logical pages
-s, --number-separator=STRING add STRING after (possible) line number
-v, --first-page=NUMBER first line number on each logical page
-w, --number-width=NUMBER use NUMBER columns for line numbers
--help display this help and exit
--version output version information and exit
By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn. CC are
two delimiter characters for separating logical pages, a missing
second character implies :. Type \ for \. STYLE is one of:
a number all lines
t number only nonempty lines
n number no lines
pBRE number only lines that contain a match for the basic regular
expression, BRE
FORMAT is one of:
ln left justified, no leading zeros
rn right justified, no leading zeros
rz right justified, leading zeros

