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

使用while循环结合sed的Bash脚本执行后th2.csv为空的问题求助

Troubleshooting & Fixing Your Bash Script Issue

Let's break down exactly what's causing your script to output an empty th2.csv and fix it step by step:

Key Problems in Your Original Script

1. Sed is Ignoring Your Pipeline Input

You added th1.csv as a parameter to your sed command, which tells sed to read the entire th1.csv file directly instead of processing the single line piped from echo "$line". This completely breaks your while loop logic—every iteration of the loop would re-process the entire file instead of the current line, leading to duplicate output (or no meaningful output if your input file is misaligned).

2. Script File Name Conflicts with Input Data File

You're running bash th1.csv > th2.csv, which means you saved your script as th1.csv. Then your script tries to read input from th1.csv—this means it's reading the script's own code, not your actual CSV data! Since your script code doesn't contain ,True, or ,False, strings, sed has nothing to replace, hence the empty output file.

3. Missing Global Flag for Second Sed Replacement

Your second substitution s/,False,/,th,/ doesn't have the g flag, so it will only replace the first occurrence of ,False, per line. Any subsequent matches in the same line would be ignored.

Fixed Script

First, save this script as a separate file (e.g., convert_csv.sh—do NOT name it th1.csv):

#!/bin/bash
while read -r line; do
    # Remove the th1.csv parameter from sed, add 'g' to second substitution
    echo "$line" | sed -E 's/,True,/,ll,/g; s/,False,/,th,/g'
done < th1.csv

How to Run It

  1. (Optional) Make the script executable:
    chmod +x convert_csv.sh
    
  2. Execute it to generate your output file:
    ./convert_csv.sh > th2.csv
    # Or if you prefer using bash directly:
    bash convert_csv.sh > th2.csv
    

Bonus: More Efficient Alternative (If You Didn't Need the While Loop)

Just for reference, you could skip the while loop entirely and let sed process the whole file directly—it's faster and cleaner:

sed -E 's/,True,/,ll,/g; s/,False,/,th,/g' th1.csv > th2.csv

But since you specifically require a while loop, the fixed script above meets your requirement perfectly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 20:42:38