简体   繁体   中英

Shell Script - CSV file change value of n'th column if column b contains the serach string

There are a lot of questions on data processing on a CSV file. But all are specific.

I have comma separated CSV file. I have already done required operations but there is one step which i am still stuck at.

Please note i am looking to make this change using Shell Script. 'AWK' or 'SED' might help me but i lack the knowledge of correct syntax for this.

Input:

Index,SrNo,Name,Desc,Target,Strength
1,125,RX,Big,NULL,236
2,246,DMT,Med,NULL,548
3,425,VT,SML,NULL,461
4,512,RX,Big,NULL,415
5,951,VT,SML,NULL,243
6,426,DMT,Med,NULL,412

I want to change the value of column 'Target' from NULL to 'ACTIVE' if The column 'NAME' is either 'RX' or 'DMT'.

Below is the expected output.

Index,SrNo,Name,Desc,Target,Strength
1,125,RX,Big,Active,236
2,246,DMT,Med,Active,548
3,425,VT,SML,NULL,461
4,512,RX,Big,Active,415
5,951,VT,SML,NULL,243
6,426,DMT,Med,Active,412

Assuming your input is comma delimited as the question says, you can use this awk:

awk 'BEGIN{FS=OFS=","} $3 ~ /^(RX|DMT)$/{$5 = "ACTIVE"} 1' file.csv

Index,SrNo,Name,Desc,Target,Strength
1,125,RX,Big,Active,236
2,246,DMT,Med,Active,548
3,425,VT,SML,NULL,461
4,512,RX,Big,Active,415
5,951,VT,SML,NULL,243
6,426,DMT,Med,Active,412

To get formatted output use column :

awk 'BEGIN{FS=OFS=","} $3 ~ /^(RX|DMT)$/{$5 = "ACTIVE"} 1' file.csv  |
column -s, -t

Index  SrNo  Name  Desc  Target  Strength
1      125   RX    Big   Active  236
2      246   DMT   Med   Active  548
3      425   VT    SML   NULL    461
4      512   RX    Big   Active  415
5      951   VT    SML   NULL    243
6      426   DMT   Med   Active  412

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM