【问题标题】:Add strings contained in a text file to end of each 4th line将文本文件中包含的字符串添加到每 4 行的末尾
【发布时间】:2017-10-06 06:24:12
【问题描述】:

我有一个文件 A.txt 和一个文件 B.txt。 B.txt 文件包含一个字符串列表(每行一个),这些字符串需要放在 A.txt 文件中每 4 行的末尾。

例子:

A.txt(我为这个例子添加了行号 - 在实际情况下没有这样的列):

1   id_line1
2   some text
3   some text
4   some text
5   id_line2
6   some text
7   some text
8   some text
9   id_line3
10  some text
11  some text
12  some text
13  id_line4
14  some text
15  some text
16  some text

B.txt

1 A
2 B
3 C
4 D

所以 B.txt 包含的行数正好是 A.txt 行数的 4 倍(每个 B.txt 行对应于 A.txt 中的第 4 行)。

最后我想要一个 C.txt 文件:

id_line1_A
some text
some text
some text
id_line2_B
some text
some text
some text
id_line3_C
some text
some text
some text
id_line4_D
some text
some text
some text

我的问题是使用 sed/awk 遍历 B.txt 文件。尽管如此,我也可以用更高级的语言(例如 pyhton)来做这件事

有什么想法吗? 谢谢

【问题讨论】:

    标签: text awk sed


    【解决方案1】:

    这是一种使用sed 的方法,但也可以使用pastexargsprintf,它们非常标准:

    sed 's:$:\n\n\n:' B.txt |
        paste -d'\n' A.txt - |
        xargs -n8 -d'\n' printf '%s_%s\n%s%s\n%s%s\n%s%s\n'
    

    大致:(1) 使文件长度相同,(2) 逐行合并,(3) 以您想要的任何格式打印。

    【讨论】:

    • 谢谢,太好了。第一个 sed 技巧是个好主意!
    【解决方案2】:

    这可能对你有用(GNU sed):

    sed '1~4R fileB' fileA | sed '1~5{N;s/\n/_/}'
    

    将一行 fileB 附加到 fileA 的每四行,并将生成的文件通过管道传递到 sed 的第二次调用中,该调用将附加的换行符替换为下划线。

    【讨论】:

      【解决方案3】:
      awk 'FNR==NR{B[NR-1]=$0;next}{if(!((FNR+3)%4))$0=$0 B[(b++ %4)]}4' FileB.txt FileA.txt
      

      里面有评论

      awk '
         # loading file B in memory, and read next line (until next file)
         FNR==NR { B[NR - 1]=$0;next}
      
         # complete file a
         {
         # 4th line (from 1st)
         # using the modulo of line numer (%) and a incremented counter (b)
         if( ! ( ( FNR + 3 ) % 4 ) ) $0 = $0 B[(b++ % 4)]
         # print every line
         print
         }
      
         # file order is mandatory
         ' FileB.txt FileA.txt
      

      【讨论】:

        【解决方案4】:

        在 Python3 中,这可以解决问题:

        with open('a.txt') as a_file:
            with open('b.txt') as b_file:
                for b_line in b_file:
                    print(next(a_file).strip()+'_', end='')
                    print(b_line, end='')
                    for _ in range(3):
                        print(next(a_file), end='')
        

        使用您的示例,它会输出:

        1   id_line1_1 A
        2   some text
        3   some text
        4   some text
        5   id_line2_2 B
        6   some text
        7   some text
        8   some text
        9   id_line3_3 C
        10  some text
        11  some text
        12  some text
        13  id_line4_4 D
        14  some text
        15  some text
        16  some text
        

        【讨论】:

          猜你喜欢
          • 2017-04-10
          • 1970-01-01
          • 2017-02-07
          • 1970-01-01
          • 1970-01-01
          • 2012-02-03
          • 2015-05-27
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多