Friday, March 10, 2017

vim - how to re-format the assignment or equation in the code and log file

From time to time, we find ourselves in the situation where  we have some code or log files that have the following format

a=10
bb=20
ccc=30
dddd=40
eeeee=50
ffffffff=60

and we want to have a cleaner format like :

a                              = 10
bb                             = 20
ccc                            = 30
dddd                           = 40
eeeee                          = 50
ffffffff                       = 60



Here are the steps how to do it quickly in vim.

step 1: add empty space before and after = sign. we can achieve this by substitue command

    '<,'>s/=/ = /

step 2: re-format each line using printf

'<,'>!xargs printf "\%-20s \%s \%s"


Explanation

'<,'> is the previous selection (type ge)
! calls the external command
xargs will pass each line to printf.
\% is to escape the % sign. In vim, % represent the current file name
-20 means the minimum size of the string is 20 and it is left-adjusted
\%-20s \%s \%s correspond to left side, = sign and right side respectively.

No comments:

Post a Comment