vim搜索并用不同的字符串替换连续的字符串出现

时间:2018-05-19 19:04:31

标签: linux vim

假设我有多次STRING次出现。我希望将第一个匹配项替换为STRING_A,将第二个匹配项替换为STRING_B,将第三个匹配项替换为STRING_C

e.g

Color of my pant is STRING. Color of my hair is STRING. Color of my car is STRING.

运行搜索和替换之后,我应该得到:

Color of my pant is STRING_A. Color of my hair is STRING_B. Color of my car is STRING_C.

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

来自vim wiki

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stack</title>
    <style type="text/css">

#recipebackground{
      /* The image used */
    background-image: url("../imgs/ajiacobackground.jpg");

    /* Full height */
    height: 50%; 
    /* Center and scale the image nicely */
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    /*opacity*/
    opacity: 0.5;
}

    </style>
</head>
<body>

<section id="recipebackground" class="opacitybox">

<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
  <section>
<div class="container" >
<h1 style="font-size: 350%;" class="text-center"><b>It's Lunch-Time!</b></h1>
</div>
</section>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
</body>
</html>

但这会给你STRING_1,STRING_2等。

轻微修改可提供所需的结果:

import json
    with open('981452637_tweetlist.json') as json_file:
        json_data = json.load(json_file)
        lst = json_file[0]['text']              #change here
        print lst

如果要从数组中获取替换,请先定义一个数组:

let @a=1 | %s/STRING/\='STRING_'.(@a+setreg('a',@a+1))/g

然后进行替换:

let @a=65 | %s/STRING/\='STRING_'.nr2char(@a+setreg('a',@a+1))/g

这会给你:

:let foo=['bar','baz','bak']

答案 1 :(得分:0)

您可以定义一个替换列表,然后使用:help sub-replace-expression弹出替换列表:

:let r = ['bar', 'baz', 'bak']
:%substitute/STRING/\=remove(r, 0)/g