Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add extra delimiters to the end of a CSV file is some are found to be missing?

Tags:

bash

csv

awk

I have a CSV file formatted like this:

A @ B @ C @ D @ E

It should have five columns, unfortunately, some are missing the last column, e.g.:

A @ B @ C @ D

How can I add an extra @ to the end of every line which is missing the last column?

like image 934
Village Avatar asked Dec 06 '22 15:12

Village


1 Answers

Assuming that the spaces are part of the field contents and the delimiter is "@" alone (although other variations can easily be accommodated):

awk 'BEGIN {FS = OFS = "@"} {$5 = $5; print}' inputfile

AWK creates missing intervening fields. Setting a field value to itself preserves existing contents if the field already exists or sets it and any intervening created fields to empty strings.

$ cat inputfile
A @ B @ C @ D @ E
A @ B @ C @ D
A @ B @ C
$ awk 'BEGIN {FS = OFS = "@"} {$5 = $5; print}' inputfile
A @ B @ C @ D @ E
A @ B @ C @ D @
A @ B @ C @@
like image 78
Dennis Williamson Avatar answered May 15 '23 03:05

Dennis Williamson