使用sed/awk/bash将缺少的行号填充到文件中

2024-04-27 15:03:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个(制表符分隔的)文件,其中每行的第一个“单词”是行号。但是,缺少一些行号。我想插入新行(带有相应的行号),以便在整个文件中,打印在行上的数字与实际行号匹配。(这是为了以后使用cut/awk进入readarray以获取行号之后的行。)

我已经用python编写了这个逻辑,并对它进行了测试,但是我需要在没有python的环境中运行它。实际文件大约有10万行。有没有一种方法可以使用sed、awk甚至是纯shell/bash来表示这种逻辑

linenumre = re.compile(r"^\d+")
i = 0
for line in sys.stdin:
    i = i + 1
    linenum = int(linenumre.findall(line)[0])

    while (i < linenum):
        print(i)
        i = i + 1

    print(line, end='')

测试文件如下所示:

1   foo 1
2   bar 1
4   qux 1
6   quux    1
9       2
10  fun 2

预期产出如下:

1   foo 1
2   bar 1
3
4   qux 1
5
6   quux    1
7
8
9       2
10  fun 2

Tags: 文件foolinebar逻辑单词制表符print
3条回答

我已经用python编写了这个逻辑并测试了它的工作原理,但是我需要在没有python的环境中运行它

如果您希望在未安装python的地方运行python代码,您可以冻结您的代码The Hitchhiker's Guide to Python概述了能够执行此操作的工具。我建议首先尝试pyinstaller,因为它支持各种操作系统,而且似乎易于使用

这可能适合您(GNU join、seq和join):

join -a1 -t' ' <(seq $(sed -n '$s/ .*//p' file)) file 2>/dev/null

使用file中的最后一行号与file连接由命令seq创建的文件

像这样,使用awk

awk '{while(++ln!=$1){print ln}}1' input.txt

解释,作为多行脚本:

{

    # Loop as long as the variable ln (line number)
    # is not equal to the first column and insert blank
    # lines.

    # Note: awk will auto-initialize an integer variable
    # with 0 upon its first usage

    while(++ln!=$1) {
        print ln
    }
}

1 # this always expands to true, making awk print the input lines

相关问题 更多 >