Howto clean comments from raw sql file

后端 未结 5 1265
时光说笑
时光说笑 2021-02-19 19:50

I have problem with cleaning comments and empty lines from already existing sql file. The file has over 10k lines so cleaning it manually is not an option.

I have a litt

5条回答
  •  被撕碎了的回忆
    2021-02-19 20:32

    It is possible to do it with regular expressions. First you have to split the file by strings and after this you can split the file by comments. The following Perl program does it:

    #! /usr/bin/perl -w
    
    # Read hole file.
    my $file = join ('', <>);
    
    # Split by strings including the strings.
    my @major_parts = split (/('(?:[^'\\]++|\\.)*+')/, $file);
    
    foreach my $part (@major_parts) {
        if ($part =~ /^'/) {
            # Print the part if it is a string.
            print $part; 
        }
        else {
            # Split by comments removing the comments
            my @minor_parts = split (/^--.*$/m, $part);
            # Print the remaining parts.
            print join ('', @minor_parts);
        }
    }
    

提交回复
热议问题