Vim practical example

delbetu

M Bellucci

Posted on July 6, 2018

Vim practical example

The problem

In my job, I had to open in a browser a set of similar URLs.
A sample URL
https://db-provider.com/dashboard.html#database/the-db-name/<element-name>.<lang>.<locale>

In this concrete case, I had to access 6 elements and each one in 6 different languages.
36 different URLs.

Solution

Approach 1
Open the browser and type every URL
This would be reaaaaaaally boring.

Approach 2
Use Vim

Open vim
Write the sample URL
Then replicate this URL 5 times.

yy5p
Enter fullscreen mode Exit fullscreen mode

Now we have one line per element.
alt 1

Write every element name

:1s/<element-name>/element1/ # scoped to line 1 replace <element-name> with element1
:<up_arrow> # show previous executed command
:2s/<element-name>/element2/
Enter fullscreen mode Exit fullscreen mode

Repeat this 4 more times
alt 2

Replicate this block 5 times once per lang-locale

ggy6jG # go to top, yank 6 lines down, go to bottom
qq # start recording in register q
o<esc> # insert blank line
p # paste yanked block
G # go to bottom
q # stop recording
Enter fullscreen mode Exit fullscreen mode

At this point, we have recorded insert a new line and paste yanked block.
Let's repeat this 5 times.

5@q # execute register q 5 times
Enter fullscreen mode Exit fullscreen mode

alt 3

gg # Go to the top
Enter fullscreen mode Exit fullscreen mode

For each block replace first lang-locale with en.us
Create a macro for replacing one line and go to next line to replace.

qq # start recording
:.s/<lang>.<locale>/en.us/ # scoped to current line replace <lang>.<locale> with en.us
7jq # go 7 lines down and stop recording
5@q # repeat this macro 5 more times once per each block.
Enter fullscreen mode Exit fullscreen mode

At this point you should have something like this:
alt 4

Go to the second line and repeat the process with de.de

2gg # go to second line
Enter fullscreen mode Exit fullscreen mode

Repeate the process with pt.BR, es.MX, fr.fr and ja.jp

At this point, you should have something like
alt 5

Remove every empty line.

:g/^$/d # apply d command to lines matching /^$/
Enter fullscreen mode Exit fullscreen mode

We have built every possible URL.
Now we need to open them into default browser.

:%! xargs open # pass all lines as the argument to open command
Enter fullscreen mode Exit fullscreen mode

magic3

The default browser will open all those URLs in different tabs.
(open command is present on mac-os. For Linux you should have a similar)

I hope you've enjoyed.
All comments are welcome!

💖 💪 🙅 🚩
delbetu
M Bellucci

Posted on July 6, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Vim practical example
vim Vim practical example

July 6, 2018