我需要找到一种更快的方法,使用 awk 和 sed 等工具以特定方式对文件中的行进行编号。我需要以这种方式对每行的第一个字符进行编号:1,2,3,1,2,3,1,2,3 等。
例如,如果输入是这样的:
line 1
line 2
line 3
line 4
line 5
line 6
line 7
输出需要如下所示:
1line 1
2line 2
3line 3
1line 4
2line 5
3line 6
1line 7
这是我所拥有的一部分。 $lines 是数据文件中的行数除以 3。因此,对于 21000 行的文件,我处理此循环 7000 次。
export i=0
while [ $i -le $lines ]
do
export start=`expr $i \* 3 + 1`
export end=`expr $start + 2`
awk NR==$start,NR==$end $1 | awk '{printf("%d%s\n", NR,$0)}' >> data.out
export i=`expr $i + 1`
done
基本上,这一次会抓取 3 行,对它们进行编号,然后添加到输出文件中。它很慢...然后还有一些!我不知道还有另一种更快的方法...有什么想法吗?
最佳答案
尝试使用nl
命令。
参见https://linux.die.net/man/1/nl (或者当您 Google 搜索“man nl”时出现的文档的另一个链接,或者当您在 shell 提示符下运行 man nl
时出现的文本版本)。
The nl utility reads lines from the named file or the standard input if the file argument is ommitted, applies a configurable line numbering filter operation and writes the result to the standard output.
编辑:不,这是错误的,我很抱歉。 nl
命令没有每 n
行重新开始编号的选项,它只有在找到模式后重新开始编号的选项。我会将这个答案作为社区 wiki 答案,因为它可能会帮助某人了解 nl
。
关于Shell 脚本对文件中的行进行编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/350701/