Regex 使用sed删除包含斜杠的行/

Regex 使用sed删除包含斜杠的行/,regex,bash,sed,Regex,Bash,Sed,我知道在某些情况下,/之外的其他字符可以在sed表达式中使用: sed-e's./..g'文件将/替换为文件中的空字符串,因为我们使用作为分隔符 但是,如果要删除文件中与//注释匹配的行,该怎么办 sed-e.//comment.d”文件返回 sed: -e expression #1, char 1: unknown command: `.' 您仍然可以使用备用分隔符: sed '\~//~d' file 只需跳过delimeter的开头一次。要删除带有注释的行,请从下面的Perl one

我知道在某些情况下,
/
之外的其他字符可以在
sed
表达式中使用:

sed-e's./..g'文件
/
替换为
文件
中的空字符串,因为我们使用
作为分隔符

但是,如果要删除
文件中与
//注释
匹配的行,该怎么办

sed-e.//comment.d”文件
返回

sed: -e expression #1, char 1: unknown command: `.'

您仍然可以使用备用分隔符:

sed '\~//~d' file

只需跳过delimeter的开头一次。

要删除带有注释的行,请从下面的Perl one行中选择。它们都使用
m{}
形式的正则表达式分隔符,而不是更常用的
/
。这样,您就不必像这样转义斜杠:
\/
,这使得双斜杠看起来不太可读:
/\/\/

创建一个示例输入文件:

echo > in_file \
'no comment
// starts with comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line'

删除以注释开头的行:

perl -ne 'print unless m{^//}' in_file > out_file
输出:

no comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line
no comment
foo // comment is anywhere in the line
no comment
删除以可选空格开头,后跟注释的行:

perl -ne 'print unless m{^\s*//}' in_file > out_file
perl -ne 'print unless m{//}' in_file > out_file
输出:

no comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line
no comment
foo // comment is anywhere in the line
no comment
删除任何地方有注释的行

perl -ne 'print unless m{^\s*//}' in_file > out_file
perl -ne 'print unless m{//}' in_file > out_file
输出:

no comment
   // starts with whitespace, then has comment
foo // comment is anywhere in the line
no comment
foo // comment is anywhere in the line
no comment
Perl one liner使用以下命令行标志:
-e
:告诉Perl在线查找代码,而不是在文件中。
-n
:在输入上一次循环一行,默认情况下将其分配给
$\uu

另请参见:



来自GNU sed的主页:
\cregexpc
:匹配与正则表达式匹配的行
regexp
c
可以是任何字符。与其使用
sed
,不如使用
grep-v/
grep-v
是POSIX,这很好