-1

例如:我有一个 txt 文件,例如:

文本(“你好”) 文本(“世界”) 文本(“曾经”) 文本(“再次”)

Aim to replace 
hello  with string_1,
world with string_2,
once with string_3,
again  with string_4,

如何编写脚本?

4

2 回答 2

0
perl -pi -e 's/hello/string_1/g;s/world/string_2/g;s/once/string_3/g;s/again/string_4/g' your_file;

上面的命令将进行就地替换。如果您希望输出到控制台,则删除“ i”。

另一种方法是:

sed -e 's/hello/string_1/g;s/world/string_2/g;s/once/string_3/g;s/again/string_4/g' your_file

awk:

awk '{gsub(/hello/,"string_1");gsub(/world/,"string_2");gsub(/once/,"string_3");gsub(/again/,"string_4");print}' your_file
于 2012-09-18T08:33:44.433 回答
0

一个不错的技术是使用替换字符串的字典。就像是:

perl -pe '%x=(
    "hello" => "string_1",
    "world" => "string_2", 
    "once" => "string_3",
    "again" => "string_4",
    );
    s/$k/$v/g while( $k, $v ) = each %x' input-file
于 2012-09-18T16:36:17.453 回答