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

3
我知道在某些情况下,sed表达式中除了/字符外还可以使用其他字符: sed -e 's.//..g' file会将file文件中的//替换为空字符串,因为我们使用.作为分隔符。
但如果您想删除file中与//comment匹配的行怎么办? sed -e './/comment.d' file返回:
sed: -e expression #1, char 1: unknown command: `.'

1
来自GNU sed的manpage:_\cregexpc:匹配与正则表达式regexp匹配的行。 c可以是任何字符。_ - Cyrus
3
可以考虑使用grep -v // <filename>替代sed - twalberg
grep -v 是 POSIX 标准,所以很好。 - user1011471
2个回答

13
你仍然可以使用替代定界符:

你可以使用替代定界符:

sed '\~//~d' file

只需在分隔符的开头转义一次即可。


0

要删除带有注释的行,请从下面的Perl单行程序中进行选择。它们都使用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

删除以可选空格开头,后跟注释的行:

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

输出:

no comment
foo // comment is anywhere in the line

删除所有包含任何注释的行

perl -ne 'print unless m{//}' in_file > out_file

输出:

no comment

Perl 的一行代码使用以下命令行标志:
-e:告诉 Perl 在行内查找代码,而不是在文件中。
-n:逐行循环输入,将其默认分配给 $_另请参阅:
perldoc perlrun: 如何执行 Perl 解释器:命令行开关
perldoc perlre: Perl 正则表达式 (regexes)
perldoc perlrequick: Perl 正则表达式快速入门

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接