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

如何通过sed正则替换指定代码段,仅保留source_dir区域内容?

问题:替换文本中的特定标记段为source_dir内容

需求:在Linux bash环境中处理文本,每个目标代码段以<<<<<<<<< <<source_dir>>开头,后续为对应内容,接着是<<<<<<<<< <<target_dir>>及内容,最后以<<<<<<<<<结尾。需要将每个该代码段替换为source_dir标记下的内容。

输入文本示例

<<<<<<<<< <<source_dir>>
tesst
<<<<<<<<< <<target_dir>>
tes23442141
<<<<<<<<<
good
safasf

<<<<<<<<< <<source_dir>>
tesst241241
<<<<<<<<< <<target_dir>>
tes23442141
<<<<<<<<<

safasfas

预期输出

tesst
good
safasf

tesst241241

safasfas

原命令及错误输出

原使用的sed命令:

sed -e ':a;N;$!ba;s#<<<<<<<<< <<source_dir>>\n\(.*\)\n<<<<<<<<< <<target_dir>>.*<<<<<<<<<#\1#g' "$target_file"

执行后错误输出:

tesst
<<<<<<<<< <<target_dir>>
tes23442141
<<<<<<<<<
good
safasf

<<<<<<<<< <<source_dir>>
tesst241241

safasfas

修正后的sed命令

sed -e ':a;N;$!ba;s#<<<<<<<<< <<source_dir>>\n\(.*\)\n<<<<<<<<< <<target_dir>>\n.*\n<<<<<<<<<#\1#g' "$target_file"

修正说明

原命令的问题在于:

  • .*默认不匹配换行符,导致<<<<<<<<< <<target_dir>>.*<<<<<<<<<无法覆盖target段的换行和内容,只匹配了部分内容。
  • 修正后的命令明确匹配target段的换行(\n)和内容(.*),直到最后的<<<<<<<<<,确保整个标记块被正确替换。

如果需要支持source_dir内容为多行的场景,可使用GNU sed的扩展正则实现非贪婪匹配:

sed -E -e ':a;N;$!ba;s#<<<<<<<<< <<source_dir>>\n(.*?)\n<<<<<<<<< <<target_dir>>\n.*?\n<<<<<<<<<#\1#g' "$target_file"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:17:18