2017-05-08 39 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的第二個調用中,該調用將下劃線替換爲附加的換行符。

相關問題