Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete specific columns from csv file maintaining same structure on output [duplicate]

Tags:

linux

bash

awk

gawk

I would like to delete column 3 and keep the same structure on output file.

input file

12,10,10,10 10,1
12,23 1,45,6,7
11  2,33,45,1,2
1,2,34,5,6

I tried

awk -F, '!($3="")' file | awk -v OFS=',' '{$1=$1}1'
12,10,10,10,1
12,23,1,6,7
11,2,33,1,2
1,2,5,6

Output desired

12,10,10 10,1
12,23 1,6,7
11  2,33,1,2
1,2,5,6

Appreciate your help

like image 981
OXXO Avatar asked Jan 21 '26 15:01

OXXO


2 Answers

Better to use sed here:

sed -E 's/^(([^,]*,){2})[^,]*,/\1/' file

12,10,10 10,1
12,23 1,6,7
11  2,33,1,2
1,2,5,6

Search regex:

  • ^: Start
  • (: Start 1st capture group
    • (: Start 2nd capture group
    • [^,]*,: Match 0 or more non-comma characters followed by a comma
    • ){2}: End 2nd capture group. {2} means match 2 pairs of above match
  • ): End 1st capture group
  • [^,]*,: Match 0 or more non-comma characters followed by a comma

Replacement:

  • \1: Back-reference to captured group #1
like image 133
anubhava Avatar answered Jan 23 '26 14:01

anubhava


sed solution:

sed -E 's/^([^,]+,[^,]+,)[^,]+,/\1/' file
  • ^ - start of the string
  • [^,]+ - match any char(s) except ,
  • \1 - points to the 1st captured parenthesized group (...)

The output:

12,10,10 10,1
12,23 1,6,7
11  2,33,1,2
1,2,5,6
like image 42
RomanPerekhrest Avatar answered Jan 23 '26 14:01

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!