Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed to remove all console.log from javascript file

Tags:

regex

bash

sed

I'm trying to remove all my console.log, console.dir etc. from my JS file before minifying it with YUI (on osx).

The regex I got for the console statements looks like this:

console.(log|debug|info|warn|error|assert|dir|dirxml|trace|group|groupEnd|time|timeEnd|profile|profileEnd|count)\((.*)\);?

and it works if I test it with the RegExr. But it won't work with sed.

What do I have to change to get this working?

sed 's/___???___//g' <$RESULT >$RESULT_STRIPPED


update

After getting the first answer I tried

sed 's/console.log(.*)\;//g' <test.js >result.js

and this works, but when I add an OR

sed 's/console.\(log\|dir\)(.*)\;//g' <test.js >result.js

it doesn't replace the "logs":

terminal screenshot

like image 442
Philipp Kyeck Avatar asked Jul 06 '11 11:07

Philipp Kyeck


People also ask

How to remove from console in js?

You can edit this list: log|debug to remove the console method you want to remove. For example,if you want to remove console log, debug, info and count, change that list to log|debug|info|count .

How do I get rid of console?

If you just want to clear the console log (not the commands), just press Ctrl + L .


2 Answers

Your original expression looks fine. You just need to pass the -E flag to sed, for extended regular expressions:

sed -E 's/console.(log|debug|info|...|count)\((.*)\);?//g'

The difference between these types of regular expressions is explained in man re_format. To be honest I have never read that page, but instead simply tack on an -E when things don't work as expected. =)

like image 178
Martin Avatar answered Sep 25 '22 12:09

Martin


You must escape ( (for grouping) and | (for oring) in sed's regex syntax. E.g.:

sed 's/console.\(log\|debug\|info\|warn\|error\|assert\|dir\|dirxml\|trace\|group\|groupEnd\|time\|timeEnd\|profile\|profileEnd\|count\)(.*);\?//g'

UPDATE example:

$ sed 's/console.\(log\|debug\|info\|warn\|error\|assert\|dir\|dirxml\|trace\|group\|groupEnd\|time\|timeEnd\|profile\|profileEnd\|count\)(.*);\?//g'
console.log # <- input line, not matches, no replacement printed on next line
console.log
console.log() # <- input line, matches, no printing

console.log(blabla); # <- input line, matches, no printing

console.log(blabla) # <- input line, matches, no printing

console.debug();  # <- input line, matches, no printing

console.debug(BAZINGA)  # <- input line, matches, no printing

DATA console.info(ditto); DATA2 # <- input line, matches, printing of expected data
DATA  DATA2

HTH

like image 35
Zsolt Botykai Avatar answered Sep 21 '22 12:09

Zsolt Botykai