in reply to perl script to search and replace comment in .aspx file

Here's something that works, but it's pretty ugly with lots of if() statements. If I had more time I would do it differently and make it much more compact.

It assumes quite a bit regarding how your code is lined up. The <%-- and --> MUST be on the same line as the <script> and </script> tags, and said tags must be the only thing on the line (and must be in the file's first column). If this is not how your code is consistently lined up, it will not work, but hopefully it is a decent enough example to get you started:

#!/usr/bin/perl use warnings; use strict; open my $fh, '<', 'file.aspx' or die "Can't open the damn file for rea +ding!: $!"; my @file_content; while ( my $line = <$fh> ){ chomp $line; if ( $line =~ /^<script>/ ){ $line = "<%-- $line"; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<\/script>$/ ){ $line .= " -->"; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<%--\s+<script>/ ){ $line =~ s/^<%--\s+//; push @file_content, "$line\n"; next; } elsif ( $line =~ /^<\/script>\s+-->/ ){ $line =~ s/\s+-->//; push @file_content, "$line\n"; next; } push @file_content, "$line\n"; } close $fh; open $fh, '>', 'file.aspx' or die "Can't open the damned file for writ +ing: $!"; print $fh @file_content; close $fh;

The file I used had these contents:

<script> </script> <%-- <script> </script> -->

Replies are listed 'Best First'.
Re^2: perl script to search and replace comment in .aspx file
by hector89 (Novice) on Jun 07, 2012 at 18:16 UTC

    but if my script structure is like this: <script type="java/js"> </script>,then its not working..any solution

      Any time you're parsing text, a lot depends on how much the patterns you're trying to match may vary. If your tags may or may not span multiple lines, or may have their attributes in different orders, or other variations, parsing them can be very complicated. (Which is why it's often a good idea to use a module if there is one.) If you know your open and close tags will always be on the same line, and never more than one pair on the same line, it could be pretty simple:

      perl -p -i -e 's|(<script.+/script>)|<%-- $1 -->| unless s|<%--(\s*<sc +ript.+/script>\s*)-->|$1|' *.aspx

      Aaron B.
      Available for small or large Perl jobs; see my home node.