Shell - How to remove a string “EES” from a record

2019-09-20 09:07发布

问题:

how do we remove EES from below input file

{"last_name":"Kiran","first_name":"kumar","sno":"1234","effe‌​ctive_date":"11/01/2‌​011","cancel_date":"‌​12/31/9999","alt_ein‌​_id_indicator":"Y","‌​alt_ein_id_employer_‌​number":"V3EES"} 

Expecting the file after transformation to look like this

{"last_name":"Kiran","first_name":"kumar","sno":"1234","effe‌​ctive_date":"11/01/2‌​011","cancel_date":"‌​12/31/9999","alt_ein‌​_id_indicator":"Y","‌​alt_ein_id_employer_‌​number":"V3"}

TIA

回答1:

Following awk should remove the EES string from 8th field or after 7th colon.

awk -F':' '{sub("EES","",$8)} 1' OFS=":"   Input_file

Will add a detailed explanation for same too shortly.

Explanation:

awk -F':' Means I am setting up field separator here, by default in awk field separator's value is space so I am setting into colon now. So it will break the lines in parts with respect to colon only.

{sub("EES","",$8)} Means, I am using substitute utility of awk, which will work on method sub(regex_to_be_subsituted,new_value,current_line/variable). So here I am giving string EES to be substituted with NULL("") in $8 means 8th field of the line(which you mentioned after 7th colon).

1 means, awk works on method of condition then action, so by writing 1 I am making condition TRUE and didn't mention any action, so by default print will happen.

OFS=":" Means, setting output field separator, by default OFS will be space so as per your Input_file I am setting it to :

Input_file Means, simply mentioning Input_file name here.

If you want to save output into same Input_file then following may help you.

awk -F':' '{sub("EES","",$8)} 1' OFS=":"   Input_file > temp_file && mv temp_file Input_file


回答2:

Use jq for parsing JSON data

jq -c '.alt_ein_id_employer_number |= sub("EES";"")' file.json
{"last_name":"Kiran","first_name":"kumar","sno":"1234","effective_date":"11/01/2011","cancel_date":"12/31/9999","alt_ein_id_indicator":"Y","alt_ein_id_employer_number":"V3"}


标签: shell awk sed