Bash Script to Convert CSV to Text File
while IFS=, read -r to read CSV lines and echo to print fields separated by spaces, like: while IFS=, read -r col1 col2 col3; do echo "$col1 $col2 $col3"; done < input.csv > output.txt.Examples
How to Think About It
Algorithm
Code
#!/bin/bash input_file="input.csv" output_file="output.txt" while IFS=, read -r col1 col2 col3; do echo "$col1 $col2 $col3" done < "$input_file" > "$output_file" # Print output file content echo "Converted text content:" cat "$output_file"
Dry Run
Let's trace the example CSV with header and two rows through the script.
Read first line
Reads line: 'name,age,city' splits into col1='name', col2='age', col3='city'
Print first line
Prints: 'name age city'
Read second line
Reads line: 'Alice,30,New York' splits into col1='Alice', col2='30', col3='New York'
Print second line
Prints: 'Alice 30 New York'
Read third line
Reads line: 'Bob,25,Los Angeles' splits into col1='Bob', col2='25', col3='Los Angeles'
Print third line
Prints: 'Bob 25 Los Angeles'
| col1 | col2 | col3 |
|---|---|---|
| name | age | city |
| Alice | 30 | New York |
| Bob | 25 | Los Angeles |
Why This Works
Step 1: Reading CSV lines
The script uses while IFS=, read -r to read each line and split it by commas into variables.
Step 2: Replacing commas with spaces
By printing the variables separated by spaces, the commas are effectively replaced with spaces in the output.
Step 3: Redirecting output
The output is redirected to a text file, creating a plain text version of the CSV content.
Alternative Approaches
tr ',' ' ' < input.csv > output.txt echo "Converted text content:" cat output.txt
awk -F',' '{for(i=1;i<=NF;i++) printf "%s%s", $i, (i==NF ? "\n" : " ")}' input.csv > output.txt echo "Converted text content:" cat output.txt
csvtool -t ',' -u ' ' cat input.csv > output.txt echo "Converted text content:" cat output.txt
Complexity: O(n) time, O(1) space
Time Complexity
The script processes each line once, so time grows linearly with the number of lines.
Space Complexity
Uses constant extra space for variables; output file size depends on input size.
Which Approach is Fastest?
Using tr is fastest but less accurate; Bash loop is simple and reliable for small to medium files.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bash while loop with IFS | O(n) | O(1) | Simple CSV with fixed columns |
| tr command | O(n) | O(1) | Very fast, simple CSV without quotes |
| awk | O(n) | O(1) | More flexible CSV processing |
| csvtool | O(n) | O(1) | Complex CSV with quotes and escapes |
IFS=, read -r in Bash to split CSV lines easily by commas.IFS=, causes the script to read whole lines without splitting fields.