【问题标题】:How do I combine 2 lines at a time, appending line1 onto line2, pulling only specific parts of each line in Bash?我如何一次合并 2 行,将 line1 附加到 line2,在 Bash 中只拉出每行的特定部分?
【发布时间】:2023-01-20 00:15:33
【问题描述】:

我有数百万个短输入文件。 PyLauncher 将在超级计算机上运行,​​并行运行数百万个 python 脚本。每个在每个输入上运行一个程序,并从每个输出中复制 2 行,然后将这 2 行附加到 results.txt。 python 脚本如下所示:

for input_file in directory:
 subprocess.run(["script_name input_file | sed -n '22p; 39p' | tee -a results.txt"], shell=True)

results.txt 将包含 2*num_input_files(百万)行,例如:

Ligand: ./input/ZINC00001677.pdbqt
1       -8.288          0          0
Ligand: ./input/ZINC00001567.pdbqt
1       -10.86          0          0
Ligand: ./input/ZINC00001601.pdbqt
1       -7.721          0          0

我想接受这个,重新排列,从第 2 行删除 1、0 和 0,然后排序,以便大多数负数排在第一位,因此它看起来像:

-10.86 ZINC00001567.pdbqt
-8.288 ZINC00001677.pdbqt
-7.721 ZINC00001601.pdbqt

我发现了这个 StackOverflow 问题:How do I sort two lines at a time in bash, using the second line as index?

但是我不能完全让命令为我的文件工作。执行速度非常重要,因此 Bash 命令或 Python 都可以工作,具体取决于哪个更快。 提前致谢!

【问题讨论】:

  • 这很容易做到,但是为了对数据进行排序,您必须将所有内容都放在内存中。那会是一个约束吗?
  • 我不确定。这将在非常快的超级计算机上运行。为了获得我在上面引用的结果文件,PyLauncher 将对所有数百万个文件运行相同的脚本,该脚本在输入文件上运行一个程序,从其输出中复制 2 行,并将它们附加到 results.txt。
  • 所以你有数百万个文件,每个文件包含数百万行。是对的吗?
  • 不,对不起。我有数百万个短输入文件。 python 脚本在每个输入上运行一个程序,并从每个输出中复制 2 行。然后将这两行附加到 results.txt,它将有 2*num_input_files 行。
  • 您的问题现在与您的 cmets 相矛盾。请重写问题说明确切地你有什么,你需要什么。您可能还想用“否定排序”来限定您的意思。你所展示的似乎是一个正常的浮点顺序

标签: python bash


【解决方案1】:

在 python 中,我会做这样的事情:

with open('input.txt', 'r') as f_inp, open('output.txt', 'w') as f_out:
    while True:
        one = f_inp.readline().strip('
')
        if not one:
            break
        two = f_inp.readline().strip('
')
        f_out.write(f'{two} - {one}
')

然后我会把它留给 sort 命令来完成排序部分。

【讨论】:

    【解决方案2】:

    如果您有足够的 RAM 来存储输出文件内容,那么您可以这样做:

    from os.path import basename
    
    INPUTFILE = 'verylargefile.txt'
    OUTPUTFILE = 'results.txt'
    
    result = []
    
    with open(INPUTFILE) as data:
        while line := data.readline():
            filename = basename(line.split()[-1])
            v = data.readline().split()[1]
            result.append(f'{v} {filename}
    ')
    
    
    with open(OUTPUTFILE, 'w') as data:
        data.writelines(sorted(result, key=lambda x: float(x.split()[0])))
    

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 1970-01-01
      • 2017-04-23
      • 2019-11-18
      • 2014-04-03
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多