Dustin Cook
Dustin Cook

Reputation: 1305

Parsing File to a New File

I am parsing a CSV file, and want to write the first token ( which is a timestamp in the form YYYY-MM-DD HH:MM:SS.sss) to an output file. I am using the following code:

#!/bin/bash
input="inputfile.csv"

while 
    IFS=',' read -r f1 f2 f3 f4 f5 f6 f7
do
    echo "$f1" > $outfile.txt
done < "$input"

The problem is that when you run the script and open the file - it only prints the last line - I would like to print each timestamp, with each one having its own line. How can I edit my code?

Upvotes: 2

Views: 36

Answers (1)

falsetru
falsetru

Reputation: 369114

The following line overwrite the output file in loop.

echo "$f1" > $outfile.txt

Use >> instead (append instead of overwite):

echo "$f1" >> $outfile.txt

Alternative using awk:

awk -F, '{print $1}' inputfile.csv > outfile.txt

Upvotes: 3

Related Questions