-1

I'm trying to delete the last 2 columns of a csv file with awk. I have tried using:

x=$(awk -v FPAT='([^,]*)|(\"[^\"]+\")' -v OFS=',' '{$10=$11=""; print $0}' ${filename} > nse.csv)

But it just deletes the data in the columns not deletes it.

For example if this is the original csv:

a,b,c,d,e,f,g,h,i,j,k
1,2,3,4,5,6,7,8,9,10,11

The nse.csv will look like this:

a,b,c,d,e,f,g,h,i,,
1,2,3,4,5,6,7,8,9,,

Instead of:

a,b,c,d,e,f,g,h,i
1,2,3,4,5,6,7,8,9
markp-fuso
  • 28,790
  • 4
  • 16
  • 36
Marco
  • 1
  • 2

1 Answers1

0

Like this With GNU awk:

awk -v FPAT='([^,]*)|("[^"]+")' -v OFS=',' '{NF-=2} 1' file

a,b,c,d,e,f,g,h,i
1,2,3,4,5,6,7,8,9
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • Just don’t try this on `1,2,3,4,5,6,7,8,9,2,3`. – user3840170 May 16 '23 at 20:31
  • 1
    Don't do that first one - doing a sub based on the contents of the fields can go wrong in various ways depending on the value of those fields, e.g. duplicates of other earlier fields as @user3840170 points out, or regexp metacharacters. If you were going to do a sub it should be `sub("("OFS"[^"OFS"]){2}$","")`. Not my downvote btw. – Ed Morton May 17 '23 at 12:58
  • By the way - in shell you don't need to escape double quotes in a single-quote delimited string so you can just write `FPAT='([^,]*)|("[^"]+")'`. – Ed Morton May 17 '23 at 12:59