'Please give me some advice on the problem of vimgolf

https://www.vimgolf.com/challenges/9v006233d72d000000000219

Start file

#!/bin/bash
a = 5
b = 10
sum = $a + $b
echo $sum

mul = $a * $b
echo $mul

End file

#!/bin/bash
a=5
b=10
sum=$((a + b))
echo $sum

mul=$((a * b))
echo $mul

=================================

The keystroke in this problem was 26 but I only get 41.

The way I used it

:%s/ = /=/g

:%s/$a/$((a/g

:%s/$b/b))/g

I don't know how to reduce keystrokes more. Please give me some advice.

vim


Solution 1:[1]

  • /g means "do the substitution on every match in the line". There is only one match for each pattern so the /gs are not necessary:

    :%s/ = /=<CR>
    :%s/$a/$((a<CR>
    :%s/$b/b))<CR>
    

    You are down to 36 keystrokes.

    See :help :s_g.

  • In this specific case, $a + $b can be matched with a single pattern, $.*b, so you could fuse the two last substitutions into a single one:

    :%s/ = /=<CR>
    :%s/$.*b/$((&))<CR>
    

    And you are down to 26 keystrokes.

    See :help s/\&.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 romainl