Shell脚本拆分文本文件时出现非预期多余换行问题求助
多余换行问题原因
你当前的代码执行逻辑为「读取行→判断是否为分割行→输出行到当前文件」,作为分割标记的前置空行被读取时,判断不属于分割行,会直接输出到前一个文件,最终导致前一个文件多了1行非预期空行。
修复方案
增加上一行内容缓存机制,遇到分割行时跳过输出前置空行即可,修改后的可运行代码如下:
#!/bin/zsh rm inputfile outputfile1 outputfile2 IFS='' printf "section1\nsection1end\n\nsection2\nsection2end\n" >inputfile echo " open outputfile1" exec 3<> outputfile1 counter=1 prev_line="" IFS=$'\n' while IFS= read line; do # 匹配到分割行时直接切换文件,跳过输出前置空行 if [[ "$line" == "section2" ]]; then echo " Matched start of section2. Close outputfile1 and open outputfile2" exec 3>&- exec 3<> outputfile2 echo "$line" >&3 echo $counter $line let "counter = $counter + 1" prev_line="" continue fi # 输出上一行缓存的内容 if [[ -n "$prev_line" ]]; then echo "$prev_line" >&3 echo $((counter-1)) $prev_line fi prev_line="$line" let "counter = $counter + 1" done <inputfile # 输出最后剩余的缓存内容 if [[ -n "$prev_line" ]]; then echo "$prev_line" >&3 echo $((counter-1)) $prev_line fi echo " Close outputfile2" exec 3>&- echo unset IFS echo `wc -l inputfile` echo `wc -l outputfile1` echo `wc -l outputfile2` echo " The above should show 5, 2, 2 as desired number of newlines in these files."
运行后输出将符合预期,outputfile1为2行、outputfile2为2行。如果你的分割匹配规则不是固定字符串,替换[[ "$line" == "section2" ]]为实际的匹配逻辑即可。
可选简化方案
如果你确认分割行前的空行一定是前一个文件的最后一行,也可以在切换文件前使用truncate直接截断最后一个换行符,无需修改整体逻辑,在exec 3>&-前添加一行:
truncate -s -1 outputfile1
该方案适配性不如缓存方案,仅适合固定规则的简单场景。
内容的提问来源于stack exchange,提问作者SteveGroom
相关产品推荐
相关产品推荐

