2017-05-08 61 views
2

我有一个文件A.txt和一个文件B.txt。 B.txt文件包含需要放在A.txt文件中每行第4行末尾的字符串列表(每行一个)。将包含在文本文件中的字符串添加到每个第4行的末尾

实施例:

A.TXT(I加入此示例的行号 - 在真实情况下,不存在这样的列):

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)

任何想法? 感谢

回答

2

这是一种与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)以任何你想要的格式打印。

+0

谢谢你的完美。第一个sed技巧是非常好的主意! –

0

在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 
0
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 
1

这可能评论为你工作(GNU sed):

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

将fileB行追加到fileA的每第四行,并将生成的文件传送到sed的第二个调用中,该调用将下划线替换为附加的换行符。

相关问题