如何使用shell命令在每一行中添加行号?

Nai*_*ita 38 shell sed awk shell-script text-processing

我的档案,

PSS-A  (Primary A)
PSS-B  (Primary B)
PSS-C  (Primary C)
PSS-D  (Primary D)
PSS-E  (Primary E)
PSS-F  (Primary F)
PSS-G  (Primary G)
PSS-H  (Primary H)
PSS-I  (Primary I)
SPARE  (SPARE)
Run Code Online (Sandbox Code Playgroud)

输出文件,

 1> PSS-A  (Primary A)
 2> PSS-B  (Primary B)
 3> PSS-C  (Primary C)
 4> PSS-D  (Primary D)
 5> PSS-E  (Primary E)
 6> PSS-F  (Primary F)
 7> PSS-G  (Primary G)
 8> PSS-H  (Primary H)
 9> PSS-I  (Primary I)
10> SPARE  (SPARE)
Run Code Online (Sandbox Code Playgroud)

jim*_*mij 61

这项工作的正确工具是nl

nl -w2 -s'> ' file
Run Code Online (Sandbox Code Playgroud)

您可能希望w根据文件中的总行数调整idth 选项(如果您希望数字很好地对齐)。

输出:

 1> PSS-A  (Primary A)
 2> PSS-B  (Primary B)
 3> PSS-C  (Primary C)
 4> PSS-D  (Primary D)
 5> PSS-E  (Primary E)
 6> PSS-F  (Primary F)
 7> PSS-G  (Primary G)
 8> PSS-H  (Primary H)
 9> PSS-I  (Primary I)
10> SPARE  (SPARE)
Run Code Online (Sandbox Code Playgroud)

  • `nl` 处理包含 1、2 或 3 个 `\:` 字符串序列的行。使用 `-d $'\n'` 来避免这种情况。此外,默认情况下,它不会为空行编号。使用 `-ba` 为每一行编号。 (4认同)
  • @myrdd, `$'...'` 来自 ksh93,并且至少也被 `zsh`、`mksh`、busybox sh、FreeBSD sh 和 bash 支持。它还不是标准,但计划包含在下一个主要 POSIX 版本中。 (2认同)

ami*_*sax 52

如果您想要与您指定的格式相同的格式

awk '{print NR  "> " $s}' inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)

否则,尽管不是标准的,该cat命令的大多数实现都可以为您打印行号(至少在 GNU、busybox、Solaris 和 FreeBSD 实现中,数字填充到宽度 6 并紧跟 TAB)。

cat -n inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)

或者,您可以将grep -n(numbers :and ) 与^匹配任何行的正则表达式一起使用:

grep -n '^' inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)

  • 另请注意,`cat -n` 不可移植。[POSIX `cat`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/cat.html) 中仅指定了 `-u` 选项。 (2认同)