如何使用"grep"从文件中删除注释?

And*_*dré 2 sql grep

我有一个SQL文件,我需要删除所有的评论

-- Sql comment line
Run Code Online (Sandbox Code Playgroud)

如何在Linux中使用GREP或其他工具实现此目的?

最好的祝福,

pax*_*blo 10

grep工具有一个-v选项,可以反转过滤器的意义.例如:

grep -v pax people
Run Code Online (Sandbox Code Playgroud)

将为您提供people文件中包含的所有行pax.

一个例子是:

grep -v '^ *-- ' oldfile >newfile
Run Code Online (Sandbox Code Playgroud)

除去评论标记前面只有空格的行.然而,它不会改变如下行:

select blah blah -- comment here.
Run Code Online (Sandbox Code Playgroud)

如果你想这样做,你会使用类似的东西sed:

sed -e 's/ --.*$//' oldfile >newfile
Run Code Online (Sandbox Code Playgroud)

它编辑每行删除任何字符" --"到行尾.

请记住,您需要小心" --"真实的 SQL语句中查找字符串,如(设计的):

select ' -- ' | colm from blah blah blah
Run Code Online (Sandbox Code Playgroud)

如果你有这些,你最好创建/使用SQL解析器而不是简单的文本修改工具.


sed正在运作的成绩单:

pax$ echo '
...> this is a line with -- on it.
...> this is not
...> and -- this is again' | sed -e 's/ --.*$//'

this is a line with
this is not
and
Run Code Online (Sandbox Code Playgroud)

对于grep:

pax$ echo '
  -- this line starts with it.
this line does not
and -- this one is not at the start' | grep -v '^ *-- '

this line does not
and -- this one is not at the start
Run Code Online (Sandbox Code Playgroud)