[英]How to delete block of code inside curly brackets?
I have a file that has some code block:我有一个包含一些代码块的文件:
dimensions{
dim1{
//foo
}
dim2{
//bar
}
}
How can I delete the whole 'dimensions' block including everything inside?如何删除整个“尺寸”块,包括里面的所有内容? Taking into consideration that I don't know how many blocks there is inside, but I'm sure that there us same number of opening and closing curly brackets?考虑到我不知道里面有多少块,但我确定我们有相同数量的左大括号和右大括号? Thanks in advance.提前致谢。
Using vim it's fairly simple to match any line that contains dimensions
using :global
:使用 vim 使用:global
匹配包含dimensions
的任何线都相当简单:
:[range]g[lobal]/{pattern}/[cmd]
eg:例如:
:g/dimensions/print
Where the command print
will print all matched lines:命令print
将打印所有匹配的行:
Changing the command to normal!
将命令更改为normal!
one can execute normal mode commands on the matched lines, eg d
elete, or y
ank.可以在匹配的行上执行正常模式命令,例如d
删除或y
ank。
:g/dimensions/normal! ...
The command d
deletes, but needs a motion following it, eg: $
to delete until the newline character, or in our case we can use %
which finds the matching pair of character, {
matches with }
, (
matches with )
etc.命令d
删除,但需要跟随它的动作,例如: $
删除直到换行符,或者在我们的例子中,我们可以使用%
找到匹配的字符对, {
匹配}
, (
匹配)
等。
:g/dimensions/normal! d%
One can invoke vim from the command line and request it to execute commands with -c
:可以从命令行调用 vim 并使用-c
请求它执行命令:
vim -c 'g/dimensions/normal! d%' [inputfile]...
Remember to save and close to avoid vim from staying open:记得保存并关闭以避免 vim 保持打开状态:
-c 'wq'
As vim can be configured to ones needs via the vimrc file and from the environment one can disable this with:由于 vim 可以通过 vimrc 文件配置为需要的,因此可以从环境中禁用它:
-u NONE
All together:全部一起:
vim -u NONE -c 'g/dimensions/normal! d%' -c 'wq' [inputfile]...
If you can use vim instead of sed, you can take profit of the non-interactive mode:如果您可以使用 vim 而不是 sed,则可以利用非交互模式获利:
vim input.txt -u NONE -c "call search('\\<dimensions{', 'w')" -c "norm maf{%d'a" -c "wq"
Be aware that this version will edit the file in place.请注意,此版本将就地编辑文件。
This method is nice because it will take into account the recursive nesting of the curly bracket blocks.这个方法很好,因为它会考虑到大括号块的递归嵌套。
However this has some issues:但是,这有一些问题:
norm
command is not easy to understand if you don't know vim norm
命令不懂vim就不好理解 Using perl
and a recursive regular expression:使用perl
和递归正则表达式:
$ cat input.txt
some text before.
dimensions{
dim1{
//foo
}
dim2{
//bar
}
}
some text after.
$ perl -0777 -pe 's/dimensions(\{(?:(?>[^{}]+)|(?1))*\})\n//' input.txt
some text before.
some text after.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.