Example Data:
"Monday","12345","Friday"
In the above file, I want to add a new column in between 12345 and Friday.
How can I do that ?
Example Data:
"Monday","12345","Friday"
In the above file, I want to add a new column in between 12345 and Friday.
How can I do that ?
To do not involve some heavy instruments (like sed or awk):
paste -d',' <(cut -d',' -f-2 file) column.file <(cut -d',' -f3- file)
This assumes that the column you want to add is saved in the file column.file.
Assuming your data is as simple as you show, you could do
awk -F, -v OFS=, '{k=$3; $3="\"new text\""; $4=k}1' file
Or,
perl -F, -lane 's/$F[1]/$F[1],"new text"/; print' file
However, this will fail with data that can contain nested commas like:
"foo", "bar,baz", "bar"
The above is a valid csv file but these solutions will treat it as having 4 fields, not 3. If your data can contain cases like that, you should use a proper csv parser instead.
column.file : awk -F, -v OFS=, '{$(NF+1)=$NF; getline $(NF-1) < "column.file"}1' file
I just had the same problem, but the cut/paste answer didn't quite work for me as I wanted a blank field, so this worked for me:
Find out how many lines you have in the file you are inserting:
wc -l file.csv
so let's say 1. gave you 30 then use a bash loop to insert a null field between fields 3 & 4:
paste -d, <(cut -d, -f-3 file.csv) <(for i in `seq 1 30`; do echo; done) <(cut -d, -f4- file.csv) > fileNew.csv