正则表达式删除块注释也删除 * 选择器 [英] Regex to remove block comments also removing * selector
问题描述
我正在尝试使用 bash 从 .css 文件中删除所有块注释.我有以下 sed 命令的正则表达式:
I am attempting to remove all block comments from .css files using bash.I have the following regex for a sed command:
sed -r '/\/(\*)*(\s)?(\w)*|(\*)(\s)?(\w)*/d'
这可以很好地去除块注释,例如:
This works fine stripping out block comments such as:
/**
* This is a comment
*/
/* this is another comment */
但它也在删除 * Selector 的实例
but it is also removing instances of the * Selector
* {
font-size: 10px;
...etc
}
我怎样才能改变当前的正则表达式来考虑这种特殊情况?还是我需要重写我的正则表达式?
How could I alter the current regex to take this special case into account? Or will I need to rewrite my regex?
澄清一下,我将遇到的评论类型:
To clarify, the kinds of comments that I will encounter:
/**
* This is a comment
*/
/* This is another comment */
/* This is also
valid
*/
/** "*/" as is { this } */
推荐答案
以下 sed
命令应该适合您:
The following sed
command should work for you:
sed '/\/\*\**/{:a;/\*\//d;N;ba}' file.css
命令搜索模式 /**
或 /*
,如果找到,则执行大括号 {cmd1;cmd2;...}
.在该块中,我首先定义了一个标签 :a
.在下一个命令中,我检查模式缓冲区是否包含结束的 */
.如果找到,我将删除模式缓冲区并开始下一个循环.否则,我通过 N
将下一行输入附加到模式缓冲区,并通过 ba
转到标签 a
.
The command searches for the pattern /**
or /*
and if it was found, it executes the block of commands between the curly braces {cmd1;cmd2;...}
. Inside that block I first define a label :a
. In the next command I check if the pattern buffer contains the closing */
. If it was found I delete the pattern buffer and start the next cycle. Otherwise I append the next line of input to the patttern buffer through N
and goto the label a
through ba
.
file.css:
/**
* This is a comment
*/
a {
font-size: 10px;
}
/* This is another comment */
li {
font-size: 12px;
}
/* This is also
valid
*/
* {
color:white;
}
/** "*/" as is { this } */
table {
color:blue;
}
输出:
a {
font-size: 10px;
}
li {
font-size: 12px;
}
* {
color:white;
}
table {
color:blue;
}
这篇关于正则表达式删除块注释也删除 * 选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!