Wednesday, October 03, 2012

VIM Tips

Recently I was working on a project to set up a new server. The new server is a replacement of existing one. One of issues I tried to resolve is to migrate permissions from the existing server to the new server. The problem is that there are too many folders to be checked, 4k folders. I need to find a way to export permissions for each folder to a text file.

Quickly I found a command to get permissions:

cacls.exe folderName

It was very nice to find out this command. Then I use Tree to export folders to text file and edited the text file as a batch file. This is a simple batch file, but a long list of folders.

@cacls folder1 > perm.txt
@cacls folder2 >> perm.txt
...
@cacls folder4000 >> perm.txt

I encountered a problem. Some of path was wrong. I think I may missed some parts of their paths. To find out which one is not valid is a challenge. I need to find a productive way to do that. I knew the following command is a convenient way to detect valid path:

@IF NOT EXIST %folder1 ECHO %folder1

I used VIM to help me to create another batch file based on my above batch file. I used the following VIM replacement command to trim my batch file:

:%s/@cacls //g
:%s/ > perm.txt//g
:%s/ >> perm.txt//g

Those are simple VIM find and replace commands. Now I have a list of paths left:

folder1
folder2
...
folder4000

Then I use find and replace with group command to repeat folders with ECHO command:

:%s/\(.*\)/\1 ECHO \1/g

where \(xxx\) is a group. Finally I insert prefixing IF command at each line the the command:

:%s/^/@IF NOT EXIST /g

where ^ is the beginning of line. With above commands, my new batch file was created.

@IF NOT EXIST folder1 ECHO folder1
@IF NOT EXIST folder2 ECHO folder2
...
@IF NOT EXIST folder4000 ECHO folder4000

Soon I found invalid folders and quickly I fixed my scripts.

0 comments: