bash脚本中的条件字符串替换

时间:2014-11-18 19:05:47

标签: regex bash shell sed scripting

我非常擅长使用脚本编写脚本,而且我正在尝试从大型CSV文件中大量更新数据。

文件结构为:

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

更改的内容是string_subtype,有时是string_type。

当我只用:

更改string_subtype值时
sed -i 's/string_subtype_old/string_subtype_new/g' $file

没有问题。

问题是当我为各个行同时更改string_type和sub_type时,为具有相同string_type的所有记录更改了sub_type

实施例

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

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

我试过

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

但所有string_type_old都被更改了!

有什么建议吗?

- 编辑 -

真实的例子:

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

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到3很简单

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

在原始4和5中,我需要在WGADG或WFOOD中更改主要类型WHOME。

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

WHOME的所有原始内容都已更改!我需要一些命令来过滤,如grep,只过滤类型为== WHOME&&的原始数据。亚型== WGADG

1 个答案:

答案 0 :(得分:1)

您只能指定一次更改子类型:

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