如何在文件的每一行的开头添加数字?
例如:
This is the text from the file.
变为:
000000001 This is 000000002 the text 000000003 from the file.
tam*_*gal 107
不要使用猫或任何其他非设计用途的工具.使用该程序:
nl - 文件的行数
例:
nl --number-format=rz --number-width=9 foobar
Run Code Online (Sandbox Code Playgroud)
因为nl是为它而制作的;-)
Ray*_*ger 35
AWK的printf的,NR
并$0
可以很容易地有超过格式化精确和灵活的控制:
~ $ awk '{printf("%010d %s\n", NR, $0)}' example.txt
0000000001 This is
0000000002 the text
0000000003 from the file.
Run Code Online (Sandbox Code Playgroud)
sar*_*old 30
你正在寻找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
...
Run Code Online (Sandbox Code Playgroud)
-w9
请求数字长度为九位数; -nrz
要求用零填充右对齐格式化数字.
最简单,最简单的选择是
awk '{print NR,$0}' file
Run Code Online (Sandbox Code Playgroud)
请参阅上面的评论,以了解为什么nl并不是真正的最佳选择。
这是一个也可以执行此操作的 bash 脚本:
#!/bin/bash
counter=0
filename=$1
while read -r line
do
printf "%010d %s" $counter $line
let counter=$counter+1
done < "$filename"
Run Code Online (Sandbox Code Playgroud)