allenhwkim
allenhwkim

Reputation: 27738

Perl replace not working as expected

I want to replace the multiple js file block to a minified version using perl command.

When I tested it on online website, it works but when I run in command line, it does not.

echo '<!doctype html>
    <html>
    <head>
      <script src="lib/angular.js"></script>
      <!-- build:js ../ute.min.js -->
      <script src="app/app.js"></script>
      <script src="app/services/uteEndpoint.js"></script>
      <!-- endbuild:js -->' |  perl -pe 's/<!-- build:js ([^ ]+) -->[^\!]+<!-- endbuild:js -->/<script src="$1"><\/script>/gm'

What am I doing wrong in command line?

I have tested here, http://www.regexe.com/, and my expected output is

<!doctype html>
<html>
<head>
  <script src="lib/angular.js"></script>
  <script src="../ute.min.js"></script>

Upvotes: 1

Views: 135

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174696

By default Perl processes the input line by line. Since you're working with multiple lines, you need to enable paragraph mode.

perl -00pe 's~<!-- build:js ([^ ]+) -->[^\!]+<!-- endbuild:js -->~<script src="$1"></script>~gm'

OR

perl -0777pe 's~<!-- build:js ([^ ]+) -->[^\!]+<!-- endbuild:js -->~<script src="$1"></script>~gm'

Example:

$ echo '<!doctype html>
>     <html>
>     <head>
>       <script src="lib/angular.js"></script>
>       <!-- build:js ../ute.min.js -->
>       <script src="app/app.js"></script>
>       <script src="app/services/uteEndpoint.js"></script>
>       <!-- endbuild:js -->' |  perl -0777pe 's/<!-- build:js ([^ ]+) -->[^\!]+<!-- endbuild:js -->/<script src="$1"><\/script>/gm'
<!doctype html>
    <html>
    <head>
      <script src="lib/angular.js"></script>
      <script src="../ute.min.js"></script>

Upvotes: 4

Related Questions