dingo_d
dingo_d

Reputation: 11680

Removing css comments with grep

I'm writing a script that will remove comments from normalize.css which looks like this:

/*! normalize.css v7.0.0 | MIT License | github.com/necolas/normalize.css */

/* Document
   ========================================================================== */

/**
 * 1. Correct the line height in all browsers.
 * 2. Prevent adjustments of font size after orientation changes in
 *    IE on Windows Phone and in iOS.
 */

html {
  line-height: 1.15; /* 1 */
  -ms-text-size-adjust: 100%; /* 2 */
  -webkit-text-size-adjust: 100%; /* 2 */
}

/* Sections
   ========================================================================== */

/**
 * Remove the margin in all browsers (opinionated).
 */

I tried with

#!/usr/bin/env sh

normalize="node_modules/normalize.css/normalize.css"
if [[ -f "$normalize" ]]; then
  grep -v "\\/\\*([^*]|[\\r\\n]|(\\*+([^*\\/]|[\\r\\n])))*\\*\\/+" $normalize > index.css
else
  echo "There is no normalize.css available."
fi

I have loaded the normalize.css via package.json

{
  "devDependencies": {
    "normalize.css": "latest"
  }
}

You can test this by saving the above package.json in a folder and running npm i. If you have node and npm you should have node_modules folder with normalize in it.

The regex101 finds the comments with above regex, but grep just outputs the same file with comments.

What am I doing wrong?

EDIT: Expected output:

html {
  line-height: 1.15;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
}

Upvotes: 1

Views: 317

Answers (1)

anubhava
anubhava

Reputation: 785471

You can use this awk command to remove all css comments that start with /* and end with */:

cat remComm.awk

function remComm() {
   if ( !m )
      m = index($0, cs);

   if ( m && p = index($0, ce) ) {
      $0 = substr($0, 1, m-1) substr($0, p+2);
      if (m = index($0, cs))
         remComm();
   }
}
BEGIN {
   cs="/*";
   ce="*/";
   m = 0;
}
{
   remComm();
   if ( !m && NF )
      print;
}

Use it as:

awk -f remComm.awk normalize.css

Output:

html {
  line-height: 1.15;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
}
  • This is non regex solution so should process big files faster.
  • This also takes care of nested comments and presence of multiple comment block per line.
  • We set start position of comment when we encounter /* and get end position when get */ in the file.
  • Using substring functions we strip off commented positions and leave rest in $0
  • function remComm is called recursively to remove multiple comments per line.
  • Using !NF we skip printing blank or whitespace lines.

Upvotes: 1

Related Questions