Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I delete a field in awk?

Tags:

sed

awk

cut

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
like image 595
Edward Avatar asked Dec 14 '20 05:12

Edward


People also ask

Can awk modify file?

In our awk code, we don't have to handle each file separately or manually control the redirection. Instead, we just change the text as the awk command reads each line from the files. The inplace extension takes care of which file is currently being processed and writes any changes back to the file automatically.

What does awk '{ print NF }' do?

The “NF” AWK variable is used to print the number of fields in all the lines of any provided file. This built-in variable iterates through all the lines of the file one by one and prints the number of fields separately for each line.

What is end awk?

END pattern: means that Awk will execute the action(s) specified in END before it actually exits.


Video Answer


2 Answers

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
like image 95
anubhava Avatar answered Sep 21 '22 17:09

anubhava


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
like image 20
RavinderSingh13 Avatar answered Sep 19 '22 17:09

RavinderSingh13