Shell 脚本对文件中的行进行编号

标签 shell sed awk

我需要找到一种更快的方法,使用 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/

相关文章:

python - 表达式 awk,python 中的字符无效

linux - 在 Bash 中从最后到第一个输出文件行

linux - 如何为新的浏览器窗口指定几何图形(例如 1280x720)?

linux - 如何在 SED 中使用变量

linux - 如果字符也在下一个单词(sed)中,如何从单词中删除字符?

awk 字段分隔符不适用于第一行

linux - 将返回命令存储在数组 Shell 中

shell - help - sed - 在任何 XxxXxx 形式的字符串之间插入空格,而不替换模式

awk 和数值小于 1.7e-308 的数值比较