Vim の数学検索と置換 質問する

Vim の数学検索と置換 質問する

時間 (分と秒) が記載されたファイルがあり、おおよそ次のようになります。

02:53 rest of line 1...
03:10 rest of line 2...
05:34 rest of line 3...
05:35 rest of line 4...
10:02 rest of line 5...
...

時間を秒数に置き換えたいと思います。理想的には、次のような魔法のコマンドを実行したいと思います。

:%s/^\(\d\d\):\(\d\d\) \(.*\)/(=\1*60 + \2) \3/g

...ここで は(=\1*60 + \2)魔法の部分です。特殊レジスタ を使用して評価の結果を挿入できることは知っています=が、正規表現の subst 部分でこれを行う方法はありますか?

ベストアンサー1

このようなもの?

:%s/^\(\d\d\):\(\d\d\)/\=submatch(1)*60+submatch(2)/

置換が a で始まる場合、\=置換は式として解釈されます。

:h sub-replace-expression以下にコピーします

Substitute with an expression           *sub-replace-expression*
                        *sub-replace-\=*
When the substitute string starts with "\=" the remainder is interpreted as an
expression.  This does not work recursively: a substitute() function inside
the expression cannot use "\=" for the substitute string.

The special meaning for characters as mentioned at |sub-replace-special| does
not apply except for "<CR>", "\<CR>" and "\\".  Thus in the result of the
expression you need to use two backslashes to get one, put a backslash before a
<CR> you want to insert, and use a <CR> without a backslash where you want to
break the line.

For convenience a <NL> character is also used as a line break.  Prepend a
backslash to get a real <NL> character (which will be a NUL in the file).

When the result is a |List| then the items are joined with separating line
breaks.  Thus each item becomes a line, except that they can contain line
breaks themselves.

The whole matched text can be accessed with "submatch(0)".  The text matched
with the first pair of () with "submatch(1)".  Likewise for further
sub-matches in ().

おすすめ記事