63

如何将数字添加到文件中每一行的开头?

例如:

这是
文本
从文件中。

变成:

000000001 这是
000000002 正文
000000003 来自文件。
4

7 回答 7

121

不要使用 cat 或任何其他不是为此而设计的工具。使用程序:

nl - 文件行数

例子:

$ nl --number-format=rz --number-width=9 foobar
$ nl -n rz -w 9 foobar # short-hand

因为 nl 是为此而生的 ;-)

于 2011-11-21T01:38:02.570 回答
36

AWK 的printfNR并且$0可以轻松地对格式进行精确灵活的控制:

~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
0000000001 This is
0000000002 the text
0000000003 from the file.
于 2011-11-21T01:38:50.187 回答
32

您正在寻找nl(1)命令:

$ nl -nrz -w9  /etc/passwd
000000001   root:x:0:0:root:/root:/bin/bash
000000002   daemon:x:1:1:daemon:/usr/sbin:/bin/sh
000000003   bin:x:2:2:bin:/bin:/bin/sh
...

-w9要求输入九位数的数字;-nrz要求使用零填充将数字格式化为右对齐。

于 2011-11-21T01:38:29.030 回答
17

cat -n thefile将完成这项工作,尽管数字格式略有不同。

于 2011-11-21T01:36:50.513 回答
8

Easiest, simplest option is

awk '{print NR,$0}' file

See comment above on why nl isn't really the best option.

于 2016-03-21T15:14:35.120 回答
5

这是一个 bash 脚本,它也可以执行此操作:

#!/bin/bash
counter=0
filename=$1
while read -r line
do
  printf "%010d %s" $counter $line
  let counter=$counter+1
done < "$filename"
于 2014-01-21T15:43:51.963 回答
4
perl -pe 'printf "%09u ", $.' -- example.txt
于 2011-11-21T15:06:56.293 回答