Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove comments from a file using "grep"?

Tags:

grep

sql

I have an SQL file that I need to remove all the comments

-- Sql comment line

How can I achieve this in Linux using GREP or other tool?

Best Regards,

like image 747
André Avatar asked Dec 05 '25 10:12

André


2 Answers

The grep tool has a -v option which reverses the sense of the filter. For example:

grep -v pax people

will give you all lines in the people file that don't contain pax.

An example is:

grep -v '^ *-- ' oldfile >newfile

which gets rid of lines with only white space preceding a comment marker. It won't however change lines like:

select blah blah -- comment here.

If you wanted to do that, you would use something like sed:

sed -e 's/ --.*$//' oldfile >newfile

which edits each line removing any characters from " --" to the end of the line.

Keep in mind you need to be careful with finding the string " --" in real SQL statements like (the contrived):

select ' -- ' | colm from blah blah blah

If you have these, you're better off creating/using an SQL parser rather than a simple text modification tool.


A transcript of the sed in operation:

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

For the 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
like image 110
paxdiablo Avatar answered Dec 08 '25 02:12

paxdiablo


You can use the sed command as sed -i '/\-\-/d' <filename>

like image 43
explorer Avatar answered Dec 08 '25 02:12

explorer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!