如何在由空行分隔的文件中重复行号

how to repeat line numbers in a file separated by an empty line

如果我的文件中有空行,我想用 1 重新开始计数。

我的文件是这样的: 猫 test.txt

333|111|222|333| 222|111|333|222|

我正在使用猫test.txt | sed 's/|/\n/g' |荷兰 输出: 1 333 2 111 3 222 4 333

5222 6 111 7 333

我想要的是在空行之后再次从 1 开始计数。 期望的输出: 1 333 2 111 3 222 4 333

1222 2 111 3 333

请帮忙?

此任务在 'awk' 或其克隆 gawk、nawk 之一中非常简单。

创建一个脚本linerecount.awk,内容为:

/^$/ { lineno=0; next}
     { print ++lineno, [=10=]}

第一行显然重置了行号并跳到下一行。 第二行递增行号,打印它,打印行。

用 gawk -f linerecount.awk 应用到你想要的任何地方。

输入:

$ cat input.txt
First line
Second line
Third line

Second part, First line
Second line
Third line

Final part, First line
Second line

输出:

$ gawk -f linerecount.awk < input.txt
1 First line
2 Second line
3 Third line
1 Second part, First line
2 Second line
3 Third line
1 Final part, First line
2 Second line