You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用sed和grep匹配file1与file2标题并合并内容的需求

文本合并解决方案

嘿,这事儿不难搞定!根据你提供的file1和file2内容,咱们可以用一段简单的Python脚本实现你想要的输出格式。先理清楚逻辑:file1里是标题+链接成对出现,file2里是匹配标题+替换标题成对出现,我们需要把它们对应起来,拼成「匹配标题 + 对应链接 + 替换标题」的序列。

实现步骤

  1. 先把file1的内容拆成标题和链接的键值对,方便后续快速查找;
  2. 再把file2的内容拆成两两一组(匹配标题和替换标题);
  3. 遍历每一组,取出匹配标题对应的链接,按要求格式拼接所有内容。

代码实现

# 读取file1内容并构建标题-链接字典
with open('file1', 'r') as f1:
    content1 = f1.read().split()
    title_link_dict = dict(zip(content1[::2], content1[1::2]))

# 读取file2内容并处理成对数据
with open('file2', 'r') as f2:
    content2 = f2.read().split()
    # 两两分组(匹配标题,替换标题)
    pairs = list(zip(content2[::2], content2[1::2]))

# 拼接最终输出内容
result = []
for title, another_title in pairs:
    if title in title_link_dict:
        result.append(title)
        result.append(title_link_dict[title])
        result.append(another_title)

# 输出结果(可以保存到文件或者直接打印)
final_output = ' '.join(result)
print(final_output)
# 如果要保存到文件:
# with open('output.txt', 'w') as out_f:
#     out_f.write(final_output)

效果验证

用你给出的示例内容测试,运行后会输出:

title1 linkabc anothertitle2 title3 linkfgh anothertitle4 title5 linklsfr anothertitle6 title7 linksdrlk anothertitle8 title9

完全符合你想要的格式~

内容的提问来源于stack exchange,提问作者DRMTV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:38:39