如何修改Bash的capture函数为匹配的org模式段落添加分隔空行
Bash 函数
capture 修改方案 修改后完整代码
capture () { local efile="$1" local charcl begorg endorg charcl_ere='^[[:space:]]*([#;!]+|@c|\/\/)[[:space:]]*' charcl_bre='^[[:space:]]*\([#;!]\+\|@c\|\/\/\)[[:space:]]*' begorg="${charcl_bre}"'Mode: org$' endorg="${charcl_bre}"'# End of org$' mdr='^Mode: org$' ; edr='^# End of org$' sed -n "/$begorg/,/$endorg/ s/$charcl_bre//p" "$efile" | # 匹配开始标记直接删除,匹配结束标记时输出空行作为段落分隔 sed -e "/$mdr/d" -e "/$edr/{g;p;d}" | # 移除末尾多余的空行,避免最后一个段落结束后多输出空行 sed -e :a -e '/^\n*$/{$d;N;ba' -e '}' }
修改说明
- 原有逻辑会直接删除开始、结束标记,导致多个匹配块的内容直接拼接没有分隔
- 调整结束标记的处理逻辑,每匹配到一个结束标记就输出一行空行,作为不同段落的分隔符
- 新增末尾空行清理逻辑,保证输出结果最后不会残留多余空行
测试效果
针对你给出的测试文件/home/flora/docs/recnotes.txt,运行capture /home/flora/docs/recnotes.txt后输出如下:
Assigns shell positional parameters or changes the values of shell options. The -- option assigns the positional parameters to the arguments of {set}, even when some of them start with an option prefix `-'. Assigns shell positional parameters or changes the values of shell options. The -- option assigns the positional parameters to the arguments of {set}, even when some of them start with an option prefix `-'. Assigns shell positional parameters or changes the values of shell options. The -- option assigns the positional parameters to the arguments of {set}, even when some of them start with an option prefix `-'.
内容的提问来源于stack exchange,提问作者Dilna
相关产品推荐
相关产品推荐

