gorn
gorn

Reputation: 8177

How can I append additional fields to each line in a CSV file?

This is not a question about appending a new line of text to a file; it's about appending data to each row.

I have over 300 lines in a CSV file, and I want to add more text to each line separated with commas (a format used for MS Excel charts).

From the ex.txt file:

12:11, 321
12:12, 23

I want to append more fields to each line, like this:

12:11, 321, 222, 55
12:12, 23, 33, 402

Upvotes: 1

Views: 3662

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

Use Paste from GNU CoreUtils

Assuming that you aren't appending a static string, your issue is that you need to read text from one file and append text from another file. That's exactly what the paste command does.

Sample Files

Contents of file1:

12:11, 321
12:12, 23

Contents of file2:

 222, 55
 33, 402

Note the leading spaces in the first column of file2. This is needed to preserve your described format, which seems to be CSV with leading spaces after each delimiter.

Sample Invocation and Output

$ paste -d, file1 file2
12:11, 321, 222, 55
12:12, 23, 33, 402

Upvotes: 2

Adam Sznajder
Adam Sznajder

Reputation: 9206

 while read line; do
     # modify $whatYouWantToAppend
     echo -e "${line} ${whatYouWantToAppend}\n" >> newTest.txt
 done < test.txt

Upvotes: 4

Related Questions