my perl script --- Trave Target directory and modify files with regex

脚本用于遍历目录下文件,并用正则表达式匹配替换目标string.

#!/usr/bin/perl -w
use strict;

# Trave Target directory and modify files under it.
# Modified files are matched using regex.
#
# V1.1

use Getopt::Long;

my $usage = q{
Usage: fix_fetch_found [options] [dir]

     Output is write back to files and marked with /*by script begin||end*/.

     options:
        dir             Dir to fix error that fetch and %found is null are out of order
        -?,--help       Display this help message
};

# process the command line

my $help = 0;
my $dirpath = $ARGV[0];

GetOptions(
    ‘help|?‘ => \$help,
    ) or die $usage;

if ($help) {
    print $usage;
    exit;
}

# main actions
my $string = get_localtime($dirpath);
my $log = $string.".log";
my $modified_log = $string."_modified.log";
Traversal($dirpath,$log);
open(Log_File,"$log") or die("Could not open ‘$log‘ for reading $!");
while(my $name = <Log_File>){
chomp($name);
my $flag = fix_file($name);
if ($flag){
	write_file_a($modified_log,$name."\n");
}
}
close(Log_File);
exit;

# fix file with filename
sub fix_file{
my ($filename) = @_;

my $flag = 0;
my $filedata = read_file($filename);
my $modified_data = modified_content($filedata);
#print "check file $filename...\n";
my $result = check_fix($modified_data,$filename);
if ($result){
	write_file_w($filename, $modified_data);
	print "fix file $filename!\n";
	$flag = 1;
}
return $flag;
}

# check whether file is modified
sub check_fix{
my ($file_1,$filename) = @_;

my $result = 1;
my $file_2 = read_file($filename);
if ($file_1 eq $file_2){
	$result = 0;
#	print "$filename is not modified!\n";
}
return $result;
}

# modify file content using regex
sub modified_content{
my($content) = @_;

#match string with /* FETCH VARS GUESSED */
$content =~ s/IF\s*\n*\s*.*%ISOPEN\s*AND\s*\(.*%FOUND\s*IS\s*NULL\s*OR.*%FOUND\n*.*\)\s*THEN\n*\s*\/\* FETCH VARS GUESSED \*\/\s*FETCH\s*([\w_]+)\s*INTO([^;]*);/\/*by script begin*\/fetch $1 into $2;\n             if $1%isopen and $1%found then\/*by script end*\//gi;

#match string without /* FETCH VARS GUESSED */
$content =~ s/IF\s*\n*\s*.*%ISOPEN\s*AND\s*\(.*%FOUND\s*IS\s*NULL\s*OR.*%FOUND\n*.*\)\s*THEN\n*\s*FETCH\s*([\w_]+)\s*INTO([^;]*);/\/*by script begin*\/fetch $1 into $2;\n             if $1%isopen and $1%found then\/*by script end*\//gi;

return $content;
}

# Trave dir and write all file path into a log
sub Traversal{
	my ($path,$file) = @_;
	my $subpath;
	my $handle;
	my $record;
if(-d $path){
	if(opendir($handle,$path)){
		while($subpath = readdir($handle)){
		if(!($subpath =~ m/^\.$/) and !($subpath =~ m/^(\.\.)$/)){
			my $p = $path."/$subpath";
			if (-d $p){
				Traversal($p,$file);
				}
			else{
				open($record,">>$file")||die("Could not open ‘$file‘ for writing $!");
				print $record($p."\n");
				close($record);
				}
			}
		}
	}
	closedir($handle);
}
return;
}

# get local time and append a string for file name
sub get_localtime{
my ($path) [email protected]_;

(my $sec,my $min,my $hour,my $day,my $mon,my $year,my $wday,my $yday,my $isdst)=localtime(time());
$year+=1900;
$mon+=1;
my $time = join("_",$year,$mon,$day,$hour,$min,$sec);
my $str = $path."_".$time;
return $str;
}

# read file
sub read_file {
my ($filename) = @_;

open my $in, ‘<‘, $filename or die "Could not open ‘$filename‘ for reading $!";
local $/ = undef;
# local $/ = undef can read all content into a variable

my $all = <$in>;
close $in;

return $all;
}

# write file w
sub write_file_w {
my ($filename, $content) = @_;

open my $out, ‘>‘, $filename or die "Could not open ‘$filename‘ for writing $!";
print $out $content;
close $out;

return;
}

# write file a
sub write_file_a{
my ($filename,$line) = @_;

open (my $out,">>$filename") or die "Could not open ‘$filename‘ for writing $!";
print $out $line;
close $out;

return;
}
时间: 2024-10-26 11:04:44

my perl script --- Trave Target directory and modify files with regex的相关文章

How to generate exe for your PERL script?

The way I am using is PAR Packer. 1.      Downloadmodule PAR Packer: http://search.cpan.org/~rschupp/PAR-Packer-1.024/lib/PAR/Packer.pm 2.      InstallPAR Packer: 2.1 Unzipthe *.tar 2.2 Go tothe directory and run "perl Makefile,pl", if you are u

[Hive - LanguageManual] Import/Export

LanguageManual ImportExport Skip to end of metadata Added by Carl Steinbach, last edited by Lefty Leverenz on May 14, 2013  (view change) show comment Go to start of metadata Import/Export Import/Export Overview Export Syntax Import Syntax Examples V

在vi中使用perltidy格式化perl代码

格式优美的perl代码不但让人赏心悦目,并且能够方便阅读. perltidy的是sourceforge的一个小项目,在我们写完乱七八糟的代码后,他能像变魔术一样把代码整理得漂美丽亮,快来体验一下吧!!! perltidy 主页: http://perltidy.sourceforge.net/perltidy.html 安装方法: 进入解压后的文件夹,然后运行一下命令 perl Makefile.PL make make test make install 用法: 配置一下vim,使得我们在写代

[转载]两个半小时学会Perl

Learn Perl in about 2 hours 30 minutes By Sam Hughes Perl is a dynamic, dynamically-typed, high-level, scripting (interpreted) language most comparable with PHP and Python. Perl's syntax owes a lot to ancient shell scripting tools, and it is famed fo

[VIM插件]fedora22编译vim7.4对perl组件支持的问题

在fedora22下,重新编译安装vim7.4的时,在编译perl组件支持时,出现如下错误: /bin/perl -e 'unless ( $] >= 5.005 ) { for (qw(na defgv errgv)) { print "#define PL_$_ $_\n" }}' > auto/if_perl.c /bin/perl /usr/share/perl5/ExtUtils/xsubpp -prototypes -typemap /usr/share/per

Use powershell script against password hacking over OWA

In my previous company Exchange OWA isn't published to internet, so this blog described my first time encountering hacker trying to hack my new company's Active directory passwords. Based on it, I wrote a powershell script running on each CAS servers

nmap -- write a nmap script

漏洞扫描 --编写Nmap脚本 2006年12月份,Nmap4.21 ALPHA1版增加脚本引擎,并将其作为主线代码的一部分.NSE脚本库现在已经有400多个脚本.覆盖了各种不同的网络机制(从SMB漏洞检測到Stuxnet探測.及中间的一些内容).NSE的强大.依赖它强大的功能库.这些库能够很easy的与主流的网络服务和协议.进行交互. 挑战 我们常常会扫描网络环境中的主机是否存在某种新漏洞,而扫描器引擎中没有新漏洞的检測方法,这时候我们可能须要自己开发扫描工具. 你可能已经熟悉了某种脚本(比如

Perl 内部结构详解

PerlGuts Illustrated Version 0.49, for perl 5.20 and older This document is meant to supplement the perlguts(1) manual page that comes with Perl. It contains commented illustrations of all major internal Perl data structures. Having this document han

How to get all the members in user group by using LDAP in Perl?

About LDAP: LDAP stands for Lightweight Directory Access Protocol. It is usually used to fetch (and sometimes update) data in a directory of people. Using Net::LDAP module in Perl can provide a way to interact with this database. Perl script to get t