KSH脚本求助:读取文件输入写入CSV同一行时输出错位问题
Fixing CSV Output Misalignment with grep in a Loop
Hey Jay, let's break down why your script is causing misaligned output and get it sorted so you can produce clean, single-line CSV entries in the FROM:,TO: format you want.
Common Issues with Your Original Approach
Chances are your script looks something like this (a typical misstep with for loops and grep):
for entry in $(cat your_input_file.txt); do grep "FROM:" <<< "$entry" grep "TO:" <<< "$entry" done > output.csv
Here's what's going wrong:
- The
for entry in $(cat ...)syntax splits your input by whitespace (not lines), so lines with spaces get broken into multiple loop iterations. - Each
grepcommand outputs its result on a new line, so yourFROM:andTO:values end up on separate rows instead of the same CSV line.
Solution 1: Process Lines with while read (for line-by-line input)
If each line in your input file contains both a FROM: and TO: value, use a while read loop to capture each full line, extract both values, and print them together in one CSV row:
#!/bin/bash # Optional: Add a CSV header echo "FROM,TO" # Read each line of the input file while IFS= read -r line; do # Extract FROM value (remove "FROM:" and trim extra spaces) from=$(echo "$line" | grep -oP 'FROM:\s*\K.*') # Extract TO value (remove "TO:" and trim extra spaces) to=$(echo "$line" | grep -oP 'TO:\s*\K.*') # Print both values on the same CSV line printf "%s,%s\n" "$from" "$to" done < your_input_file.txt > output.csv
Solution 2: Group Multi-line Entries with awk
If your input has FROM: and TO: on separate lines (like the sample below), use awk to pair them up and output single CSV rows:
Sample input:
FROM: alice@example.com TO: bob@example.com FROM: charlie@example.com TO: dave@example.com
Here's the awk script to handle this:
awk ' # Capture FROM value when we hit a FROM line /FROM:/ { from = substr($0, 6) } # Skip "FROM:" (first 5 characters) # When we hit a TO line, print the paired FROM/TO as CSV /TO:/ { to = substr($0, 4) # Skip "TO:" (first 3 characters) printf "%s,%s\n", from, to } ' your_input_file.txt > output.csv
Key Notes
- Use
printfinstead ofechofor consistent output (avoids issues with special characters). - If your values might contain commas, wrap them in double quotes like this:
printf "\"%s\",\"%s\"\n" "$from" "$to"to comply with CSV standards.
内容的提问来源于stack exchange,提问作者jay
相关产品推荐
相关产品推荐

