Home > Back-end >  unix command to replace a string with null in a csv file
unix command to replace a string with null in a csv file

Time:04-01

I have a csv file with multiple headers and their corresponding records as below-

NA,A,B,C
$H,1,2,3
NA,D,E,F
$R,4,5,6
NA,G,H,I
$R,7,8,9
NA,J,K,L
$R,10,11,12

Please note the rows starting with NA are headers. need to replace 'NA' with null. So my expected output will be-

,A,B,C
$H,1,2,3
,D,E,F
$R,4,5,6
,G,H,I
$R,7,8,9
,J,K,L
$R,10,11,12

I have tried the below code , but did not work-

awk -F '|' -v OFS='|' '$1 == "NA" { $1 = "" }1' test.csv >test_n.csv

CodePudding user response:

Changing the FS in your code would have worked

$ awk 'BEGIN{FS=OFS=","}$1=="NA"{$1=""}1' input_file
,A,B,C
$H,1,2,3
,D,E,F
$R,4,5,6
,G,H,I
$R,7,8,9
,J,K,L
$R,10,11,12

CodePudding user response:

Using a fairly simple sed:

sed 's/^NA,/,/' file

,A,B,C
$H,1,2,3
,D,E,F
$R,4,5,6
,G,H,I
$R,7,8,9
,J,K,L
$R,10,11,12
  • Related