10

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 ?

1
  • Is your goal achieving this using awk or is it simply inserting a new column? If the latter, then the easiest way would be to use a spreadsheet application like LibreOffice Calc - it can import and export CSV files. Commented Mar 2, 2015 at 11:24

3 Answers 3

10

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.

1
  • 1
    Neat trick! Never heard of paste... Commented Nov 17, 2022 at 21:29
3

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.

1
  • In case that all lines in new column is same and == "new text" but in most cases it is not true. If new column is stored in column.file : awk -F, -v OFS=, '{$(NF+1)=$NF; getline $(NF-1) < "column.file"}1' file Commented Mar 2, 2015 at 13:00
0

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:

  1. Find out how many lines you have in the file you are inserting:

    wc -l file.csv
    
  2. 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
    

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.