tangbinde 发表于 2015-12-26 08:37:12

一段用来清除C++/C代码中空白行的perl脚本

  用Umbrello自动生成框架之后,里面有很多临时用不着的空行,而且生成的头文件都是单词开头大写字母,但是到了内部的#include就成了小写,于是写了个脚本解决这个问题
  对于#ifndef..#define .. #endif在 #define行之后及 #endif行之前会各加一个空行
  perl对我而言是救急语言,写的草率,将就着用吧……
  使用:
  ls *.cpp *.h|./changeFile.pl
  



#!/usr/bin/perl -w
#TO DO:
#replace all header includes which are in lowercase
#remove all blank lines
#among all the .cpp files in the argument list
@headers= qw/ActThread.hInvalidSettingsException.hPacketHeader.h   QString.h QObject.h QThread.h SniffThread.h DialogManager.hLuaSetDialog.h            PacketList.h      Thread.h Exception.h      LuaSettings.h               SetDialog.h       ThreadManager.h HttpSetDialog.hLuaThread.h               Settings.h HttpSettings.h   MainWindow.hSniffSetDialog.h HttpThread.hPacket.hSniffSettings.h/;
sub editFile {
    $fileName=$_;
    $tmpFileName=$fileName.".tmp";
    if($fileName ne "." && $fileName ne "..") {
      if(! open READFILE,$fileName) {
            die "Cannot open file";
      }
      if(! open TMPFILE,">".$tmpFileName) {
            die "Cannot create file";
      }
      print "File Name :".$fileName."\n";
      while(<READFILE>) {
            if(/^\n/) {
                #print "BlankLine";
            }else{
                $line=$_;
                if(!/_H/) {
                  foreach $headerFile (@headers) {
                        if(/($headerFile)/i){
                            $line=~s/$1/$headerFile/;
                        }
                  }
                }
                if(/endif/){ print TMPFILE "\n";}
                print TMPFILE $line;
                if(/define/){ print TMPFILE "\n";}
            }
      }
      close READFILE;
      close TMPFILE;
      `rm $fileName`;
      `mv $tmpFileName $fileName`;
    }
}
while(<>){
chomp($_);
editFile($_);
}
  
页: [1]
查看完整版本: 一段用来清除C++/C代码中空白行的perl脚本