Nicolas BADIA
Nicolas BADIA

Reputation: 5852

Remove code between special comments from file

Let's say I have this code :

some code 1

// @if (debug)
code to remove
// @endif

some code 2

// @if (debug)
code to remove
// @endif

some code 2

I want to remove all the codes between // @if (debug) and // @endif. For this, I've found a sed command which works if there is only one instance of // @if (debug) but doesn't if there is several one, because sed doesn't support non-greedy matches (and so, in the example above, removes also some code 2). Here is the command:

sed -r -n '1h;1!H;${;g;s/\/\/\s*@if\s*\(\s*debug\s*\)([^\0]*?)\/\/\s*@endif//g;p;}' file_path.js > file_path.min.js

I've read that I could use perl which supports non-greedy matches but I wasn't able to make it works. Here is what a try:

perl -pe 's/\/\/\s*@if\s*\(\s*debug\s*\)([^\0]*?)\/\/\s*@endif//g' file_path.js > file_path.min.js
perl -0pe 's/\/\/\s*@if\s*\(\s*debug\s*\)([^\0]*?)\/\/\s*@endif//g' file_path.js > file_path.min.js
perl -0777 -pe 's/\/\/\s*@if\s*\(\s*debug\s*\)([^\0]*?)\/\/\s*@endif//g' file_path.js > file_path.min.js

Any idea on how I could make it works with sed, perl or any other tool like this ?

Upvotes: 1

Views: 123

Answers (2)

Slaven Rezic
Slaven Rezic

Reputation: 4581

A perl solution using the flip-flop operator:

perl -nle 'm{//\s*\@if\s*\(\s*debug\s*\)}..m{//\s*\@endif} or print' file_path.js

Remember to escape the @, otherwise @if and @endif are interpreted as array variables (-w will warn about it).

Upvotes: 2

devnull
devnull

Reputation: 123608

Using sed:

$ sed '/^\/\/ @if (debug)/,/^\/\/ @endif/d' inputfile
some code 1


some code 2


some code 2

Upvotes: 5

Related Questions