简体   繁体   中英

Conditional string substitution in a bash script

I'm quite new to bash scripting and I'm trying to do a massive update of data from large CSV files.

The file structure is:

date|id|id|000000|string_type|0|0|0.00|0|0|0|0|0|0|string_subtype.

What is changed is string_subtype and sometimes the string_type.

When I only change the string_subtype value with:

sed -i 's/string_subtype_old/string_subtype_new/g' $file

there are no problems.

The problem is when I change string_type and sub_type at the same time for individual rows, the sub_type is changed for ALL records with the same string_type

Example

from

date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeA
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeA
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeB
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeB
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeC
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeC

to

date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeD
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeD
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeE
date|id|id|000000|typeA|0|0|0.00|0|0|0|0|0|0|subtypeE
date|id|id|000000|typeB|0|0|0.00|0|0|0|0|0|0|subtypeF
date|id|id|000000|typeB|0|0|0.00|0|0|0|0|0|0|subtypeF

I tried with

sed -e 's/string_type_old/string_type_new/g' -e 's/string_subtype_old/string_subtype_new/g' $file

but all string_type_old are changed!

Any suggestions?

--edit--

real example:

from

2014-01-01|000fc55|297633835|122350|WHOME|0|0|0.00|2|0|0|0|0|0|WHOME_CLEAN
2014-01-01|000fc56|297633835|122377|WHOME|0|0|0.00|2|0|0|0|0|0|WHOME_STORA
2014-01-01|000fc57|297633835|122378|WHOME|0|0|0.00|2|0|0|0|0|0|WHOME_OTHER
2014-01-01|000fc58|297633835|122428|WHOME|0|0|0.00|2|0|0|0|0|0|WHOME_KGADG
2014-01-01|000fc59|297633835|120776|WHOME|1|0|0.00|0|0|0|0|0|0|WFOOD_GOURT

to

2014-01-01|000fc55|297633835|122350|WHOME|0|0|0.00|2|0|0|0|0|0|W_CLEAN
2014-01-01|000fc56|297633835|122377|WHOME|0|0|0.00|2|0|0|0|0|0|W_STORA
2014-01-01|000fc57|297633835|122378|WHOME|0|0|0.00|2|0|0|0|0|0|W_OTHER
2014-01-01|000fc58|297633835|122428|WGADG|0|0|0.00|2|0|0|0|0|0|W_KGADG
2014-01-01|000fc59|297633835|120776|WFOOD|1|0|0.00|0|0|0|0|0|0|W_GOURT

Raws 1 to 3 is simple with

sed -i 's/WHOME_CLEAN/W_CLEAN/g' $file

sed -i 's/WHOME_STORA/W_STORA/g' $file

sed -i 's/WHOME_OTHER/W_OTHER/g' $file

In raws 4 and 5 I need to change the main type WHOME in WGADG or WFOOD.

with

sed -e 's/WHOME/WGADG/g' -e 's/WHOME_KGADG/W_KGADG/g' $file

all raws with WHOME are changed! I need of some command that filter, as grep, only the raws with type==WHOME && subtype==WGADG

您只能指定一次更改子类型,如下所示:

sed '0,/string_subtype_old/s/string_subtype_old/string_subtype_new/'

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