Can I delete a field in awk?

It's a bit heavy-handed, but this moves each field after field 2 down a place, and then changes NF so the unwanted field is not present:

$ awk -F, -v OFS=, '{ for (i = 2; i < NF; i++) $i = $(i+1); NF--; print }' test.txt
0x01,0x93,0x65,0xF8
0x01,0x01,0x03,0x02,0x00,0x64,0x06,0x01
0x01,0x00,0x76
$

Tested with both GNU Awk 4.1.3 and BSD Awk ("awk version 20070501" on macOS Mojave 10.14.6 — don't ask; it frustrates me too, but sometimes employers are not very good at forward thinking). Setting NF may or may not work on older versions of Awk — I was a little surprised it did work, but the surprise was a pleasant one, for a change.


I believe simplest would be to use sub function to replace first occurrence of continuous ,,(which are getting created after you made 2nd field NULL) with single ,. But this assumes that you don't have any commas in between field values.

awk 'BEGIN{FS=OFS=","}{$2="";sub(/,,/,",");print $0}' Input_file

2nd solution: OR you could use match function to catch regex from first comma to next comma's occurrence and get before and after line of matched string.

awk '
match($0,/,[^,]*,/){
  print substr($0,1,RSTART-1)","substr($0,RSTART+RLENGTH)
}' Input_file

All the existing solutions are good though this is actually a tailor made job for cut:

cut -d, -f 1,3- file

0x01,0x93,0x65,0xF8
0x01,0x01,0x03,0x02,0x00,0x64,0x06,0x01,0xB0
0x01,0x00,0x76

If you want to remove 3rd field then use:

cut -d, -f 1,2,4- file

To remove 4th field use:

cut -d, -f 1-3,5- file

Tags:

Awk

Sed

Cut