Tag: vim

[Vim]用行号参与替换

一个小技巧。Vim有好处千种,”替换”只是其中一个。

除了强大的正则表达式,\=也是一个好用的工具。
比如要生成这么一个文件

This is number 1
This is number 2
This is number 3
This is number 4
This is number 5
This is number 6
This is number 7
This is number 8
This is number 9
This is number 10

方法当然有很多。用\=可以这么做:
先输入一行

This is number X

复制出另外9行

yy9p

得到

This is number X
This is number X
This is number X
This is number X
This is number X
This is number X
This is number X
This is number X
This is number X

然后冒号进入Command-line模式 (关于Vim的几种模式)

:%s@X@\=line('.')

就得到了

This is number 1
This is number 2
This is number 3
This is number 4
This is number 5
This is number 6
This is number 7
This is number 8
This is number 9
This is number 10

\=其实就是对\=之后的表达式求值用来做替换。line(‘.’)是一个返回数值的函数,返回当前行的行号,所以每一行的行号被作为\=的返回值,用来替换X,就得到了需要的结果。

其他方法比如做一个宏(Macro)来逐行递增也可以达到效果,但是不如用这个\=方便。
因为\=后面的部分是作为表达式来处理的,所以更复杂一些的替换都可以很简单的得到实现,比如 (先撤销掉之前的改动,下同):

:%s@X@\=line('.')*line('.')

就可以得到

This is number 1
This is number 4
This is number 9
This is number 16
This is number 25
This is number 36
This is number 49
This is number 64
This is number 81
This is number 100

我个人觉得最好用的是这个功能

:%s@X@\=printf("%03d", line('.'))

可以得到

This is number 001
This is number 002
This is number 003
This is number 004
This is number 005
This is number 006
This is number 007
This is number 008
This is number 009
This is number 010

printf的加入又带来了太多种可能的玩法,非常称手。

Linux Tips (1)

这里记录一些小技巧,比较杂。

1. bash下,x{a,b}会被展开为xa xb,很适合文件备份。
如果你要复制一份a.txt作为备份,到a.txt的路径又太长了,这么写比较方便。

cp /a/long/long/long/path/to/file/a.txt{,bak}

2. vim下,要把某些内容替换成为行号,可以用\=line(“.”)来处理。“.”用来连接行号和其它内容。

:%s/xxxx/\=line(".") . " "/g

3. bash脚本下,如果要写多行到文件里,可以用

cat > file << EOF
file content line 1
file content line 2
file content line 3
file content line 4
EOF

这是一种固定写法,从第二行起,遇到EOF就停止,把之前的内容写到file里。EOF也可以换成别的。

4. Trap SIGINT的时候记得要处理SIGINT信号。

#! /bin/bash

trap "echo 'hello'; exit 1" SIGINT SIGTERM

while [ 1=1 ];
do
    sleep 1
done

exit 1这部分是必须的,否则虽然按下Ctrl + C的时候会显示hello,但是脚本不会被终止。

Project-Specific Vim Configuration

Usually, we have our own vim configuration in the file ~/.vimrc
What if we want one for our project?
For example, we are working on certain project which needs to read in a tags file.
Well, here is a possible solution.

You put a line at then end of your ~/.vimrc file

source ./.project.vim

Then for each project, put your project-specific stuff in a the file “.project.vim”.

If you don’t want the error message says vim cannot find the file “.project.vim”,
wrap the line above with an if statement:

if filereadable("./.project.vim")
    source ./.project.vim
endif

:]