Search code examples
awksedcut

Can I delete a field in awk?


This is test.txt:

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

If I run awk -F, 'BEGIN{OFS=","}{$2="";print $0}' test.txt the result is:

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

The $2 wasn't deleted, it just became empty. I hope, when printing $0, that the result is:

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

Solution

  • 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