如何将数字添加到文件中每一行的开头?
例如:
这是 文本 从文件中。
变成:
000000001 这是 000000002 正文 000000003 来自文件。
如何将数字添加到文件中每一行的开头?
例如:
这是 文本 从文件中。
变成:
000000001 这是 000000002 正文 000000003 来自文件。
不要使用 cat 或任何其他不是为此而设计的工具。使用程序:
nl - 文件行数
例子:
$ nl --number-format=rz --number-width=9 foobar
$ nl -n rz -w 9 foobar # short-hand
因为 nl 是为此而生的 ;-)
AWK 的printf,NR
并且$0
可以轻松地对格式进行精确灵活的控制:
~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
0000000001 This is
0000000002 the text
0000000003 from the file.
您正在寻找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
要求使用零填充将数字格式化为右对齐。
cat -n thefile
将完成这项工作,尽管数字格式略有不同。
Easiest, simplest option is
awk '{print NR,$0}' file
See comment above on why nl isn't really the best option.
这是一个 bash 脚本,它也可以执行此操作:
#!/bin/bash
counter=0
filename=$1
while read -r line
do
printf "%010d %s" $counter $line
let counter=$counter+1
done < "$filename"
perl -pe 'printf "%09u ", $.' -- example.txt