Text 将文本文件中包含的字符串添加到每个第四行的末尾
我有一个文件a.txt和一个文件B.txt。B.txt文件包含一个字符串列表(每行一个),这些字符串需要放在a.txt文件中每个第四行的末尾 例如: A.txt(我在本例中添加了行号-在实际情况中没有这样的列): B.txt 因此,B.txt包含的行数正好是A.txt行数的4倍(每个B.txt行对应于A.txt中的第4行) 最后,我想要一个C.txt文件,如下所示:Text 将文本文件中包含的字符串添加到每个第四行的末尾,text,awk,sed,Text,Awk,Sed,我有一个文件a.txt和一个文件B.txt。B.txt文件包含一个字符串列表(每行一个),这些字符串需要放在a.txt文件中每个第四行的末尾 例如: A.txt(我在本例中添加了行号-在实际情况中没有这样的列): B.txt 因此,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 som
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)来做
有什么想法吗?
谢谢这里有一种使用
sed
的方法,但也可以使用paste
、xargs
和printf
,这是非常标准的:
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)以您想要的格式打印。在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
里面有评论
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
这可能适用于您(GNU-sed):
在fileA的每四行中添加一行fileB,并将生成的文件导入sed的第二次调用,该调用将用下划线替换附加的换行符。谢谢,这太完美了。第一个sed技巧是一个非常好的主意!
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
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
sed '1~4R fileB' fileA | sed '1~5{N;s/\n/_/}'