André
André

Reputation: 25554

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

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,

Upvotes: 2

Views: 2765

Answers (3)

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

Try using sed on shell:

sed -e "s/(--.*)//" sql.filename

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881403

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

Upvotes: 10

explorer
explorer

Reputation: 335

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

Upvotes: 1

Related Questions