sed / awk替换句子特定位置的单词

时间:2011-04-26 10:05:03

标签: regex shell unix sed awk

我正在尝试替换某一行的特定位置的单词

例如,给定:

INSERT INTO address (city_id,city) VALUES (1,'Monrovia');
INSERT INTO address (city_id,city) VALUES (2,'Brunswick');
INSERT INTO address (city_id,city) VALUES (3,'Phenix City');

我想用“底特律”替换所有不同的城市,结果是:

INSERT INTO address (city_id,city) VALUES (1,'Detroit');
INSERT INTO address (city_id,city) VALUES (2,'Detroit');
INSERT INTO address (city_id,city) VALUES (3,'Detroit');

请问,我怎样才能在sed,awk或vim中这样做?

谢谢。

2 个答案:

答案 0 :(得分:3)

咦?这很简单:

$ echo "INSERT INTO address (city_id,city) VALUES (1,'Monrovia');
> INSERT INTO address (city_id,city) VALUES (2,'Brunswick'); 
> INSERT INTO address (city_id,city) VALUES (3,'Phenix City');" | 
> sed "s/'[^']*'/'Detroit'/g"
INSERT INTO address (city_id,city) VALUES (1,'Detroit'); 
INSERT INTO address (city_id,city) VALUES (2,'Detroit'); 
INSERT INTO address (city_id,city) VALUES (3,'Detroit');

干杯。基思。

答案 1 :(得分:2)

最简单:保留脚本,追加

UPDATE address SET city ='Detroit'

在vim中:

:g/^INSERT INTO address/normal f;F'ci'Detroit

在sed:

sed "s/\(VALUES (.*,\)'.*\?'/\1'Detroit'/g"