如何在文件的每一行开头添加数字?
例如:
This is the text from the file.
变成:
000000001 This is 000000002 the text 000000003 from the file.
如何在文件的每一行开头添加数字?
例如:
This is the text from the file.
变成:
000000001 This is 000000002 the text 000000003 from the file.
不要使用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.
public static final int CONSTANTX;
的东西,我想要类似于public static final int CONSTANTX;=X
的东西,其中X
是源文件中的行号。我将您的答案重新排列为awk '{printf("%s = %d;\n", $0, NR-4)}' Constants.java
,它像魔法一样奏效! - afe你正在寻找 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
要求数字为9位数;-nrz
要求将数字格式化为右对齐且用零填充。
awk(1)
在这样的任务上确实表现出色。 - sarnoldawk
和一些循环可能需要2个小时才能弄清楚如何做到这一点,而脚本运行文件还需要另外30分钟;或者我可以在这里问问。我以前从未听说过nl
。我发错了问题吗? - Villagecat -n thefile
会完成任务,虽然数字格式略有不同。
awk '{print NR,$0}' file
参见上述评论,说明nl并不是最佳选项。
#!/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
ls | nl #nl for dummies
翻译为:使用ls
命令列出文件并通过管道符号|
将结果传递给nl
命令,最后使用#nl for dummies
作为注释。 - Aaron Blenkush2 sd
$ awk '{print NR,$0}' test123 1 123 2 3 sd - egorulz-ba
开关。 - Hynek -Pichi- Vychodil