Javascript 删除了 bash 单行注释

Javascript singleline comments removed with bash

我已经尝试让它工作了一段时间,但没有成功。我知道有关于此主题的类似帖子,但他们的示例不起作用,或者他们的正则表达式对我来说过于暴力。 这太重了: Comprehensive RegExp to remove JavaScript comments

我的问题很简单,我有一个用 deploy.sh 脚本创建的统一 javascript 文件,我想删除第一个字符为“//”的每一行,忽略任何前面的空格和制表符是这样的:

// Remove this line
var foobar = "sometext";
    // remove this line with tab(s) before comment
    function foobar(); // Do not remove this!
  // remove this line with whitespace(s) before comment

这应该通过 linux/ubuntu 在 shellscript 中执行的本机工具或程序语言来实现,而无需使用任何外部文件,例如 sed。

我认为将这些条件用于注释行作为可移动的约定应该非常简单,并且误解的风险最小。如果我想在生产版本中显示一些评论,我可以使用多行评论注释 /* Comment */

通过 'grep -v' 进行管道传输应该可行,即像这样的东西(未经测试):

grep -Ev '^[ \t]*//' file > newfile

Grep 的 -v 标志反转匹配:它将所有与正则表达式不匹配的行打印到标准输出。 do 匹配的行(您的注释行)将被忽略。

只需告诉 grep 丢弃以零个或多个 space 序列开头的所有内容,然后是 //:

$ grep -v "^\s*//" file
var foobar = "sometext";
    function foobar(); // Do not remove this!