I have an issue where a client needs to duplicate a column in a CSV file. The values are always going to be identical and unfortunately our API doesn't allow for duplicate columns to be specified in the JSON.
For example I have the following column structure and values:
Name, Surname, City, Age, Job
John, Doe, Johannesburg, 28, Technical Support
Now I need to duplicate City so the output should be:
Name, Surname, City, City Again, Age, Job
John, Doe, Johannesburg, Johannesburg, 28, Technical Support
The column needs to be placed after that which will be duplicated. The value is also dependent on this first column.
awk
can handle this easily:
awk 'BEGIN{FS=OFS=", "} {$3 = $3 OFS $3} 1' file.csv
Name, Surname, City, City, Age, Job
John, Doe, Johannesburg, Johannesburg, 28, Technical Support
Note that this does the job in single and shorted command that is easy to read and is far more efficient than pipeline command that involves calling cut
twice and then a `paste.
As @codeforester rightly commented below, cut
doesn't let a column be repeated in the output; it is used for stripping out a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With