yeker3
yeker3

Reputation: 141

awk comand for inserting new column in csv

I'm using this command line I found on internet to add a new column in a csv file:

awk '{print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,F,$12,$13,$14,$15,$16}' FS=, OFS=, F='0' file.csv

So the problem is this line only prints the result in terminal but I want to modify the file.csv, would this be possible? Further more when I execute this command line the output I get is this:

original CSV:

11;ALE;Augsburg;1;Jentzsch;Simon Jentzsch;35;28;28;28;0;2520;1;0;-41;t
11;ALE;Augsburg;2;Verhaegh;Paul Johannes Gerardus Verhaegh;28;26;26;25;0;2333;3;0;1;t
11;ALE;Augsburg;18;Callsen-Bracker;Jan-Ingwer Callsen-Bracker;27;30;25;24;5;2310;7;0;4;t

Terminal Output:

,,,,,,,,,,,0,,,,,;Jentzsch;Simon Jentzsch;35;28;28;28;0;2520;1;0;-41;t
,,,,,,,,,,,0,,,,,;Verhaegh;Paul Johannes Gerardus Verhaegh;28;26;26;25;0;2333;3;0;1;t
,,,,,,,,,,,0,,,,,8;Callsen-Bracker;Jan-Ingwer Callsen-Bracker;27;30;25;24;5;2310;7;0;4;t

It is hard to explain but what I wanted was something like that:

11;ALE;Augsburg;1;Jentzsch;Simon Jentzsch;35;28;28;28;0;0;2520;1;0;-41;t
11;ALE;Augsburg;2;Verhaegh;Paul Johannes Gerardus Verhaegh;28;26;26;25;0;0;2333;3;0;1;t
11;ALE;Augsburg;18;Callsen-Bracker;Jan-Ingwer Callsen-Bracker;27;30;25;24;5;0;2310;7;0;4;t

So just add a 0 as a new column after the original 11th column. Thanks in advance!

Upvotes: 0

Views: 109

Answers (2)

Ed Morton
Ed Morton

Reputation: 203615

$ echo 'a;b;c;d' | awk '{sub(/([^;]*;){2}/,"&0;")}1'
a;b;0;c;d

Just change the 2 to 11 or whatever...

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

Something like,

$ awk -F";" -v OFS=";" '$11=$11OFS"0"' file
11;ALE;Augsburg;1;Jentzsch;Simon Jentzsch;35;28;28;28;0;0;2520;1;0;-41;t
11;ALE;Augsburg;2;Verhaegh;Paul Johannes Gerardus Verhaegh;28;26;26;25;0;0;2333;3;0;1;t
11;ALE;Augsburg;18;Callsen-Bracker;Jan-Ingwer Callsen-Bracker;27;30;25;24;5;0;2310;7;0;4;t

You won't be able to redirect the output to the file as we are reading from the same file, so we can redirect it to a new file and move the new file as old file.

Example

$ awk -F";" -v OFS=";" '$11=$11OFS"0"' file > new_file && mv new_file file

Edit

If you are using awk version 4.1.0 or later, you can use -i option as well.

$ awk -i inplace -F";" -v OFS=";" '$11=$11OFS"0"{print}' file

which will edit the file in place. Thanks @JamesBrown for the link.

Upvotes: 2

Related Questions