perl example!

example 1:
my a=OFC33L40.0
perl  '/(\d+)(?=\D)/ and print $1'  $

example2:
#!/opt/exp/bin/perl
use strict;
while(<>){
#       s/\Q[0-9]\E(?:[^+*\/])/[0-9]+/g;
        s/\[0-9](?:[^+*\/])/[0-9]+/g;
        print;
}
#!/opt/exp/bin/perl
use strict;
my $line = 0;
while(<>){
        $line++;
        print "line7 line=$line \n";
        if(s/d01/sprintf("d%02d",$line)/ge){
                print;
        }
}
example 3:
remove  felixzh1
#!/usr/bin/perl -w
use strict;
$^I = '.bak';
#read ARGV (read command line parameter file one line by one line and one file by one file)
while (<ARGV>) {
    s/felixzh1//g;
print;
}
 
it is the same with perl command line
perl  -i.bak  -pe 's/felixzh1//g' filename
 
example 4: 删除felixzh1所在的行
-n相当于-p只是不打印原来的文件内容。
-p会把每一行打出来
perl -n -e 'print unless(/felixzh1/);' < file
perl -n -e '/felixzh1/ || print' < file
perl -n -e 'print unless(/felixzh1/);' < file
perl -e 'while(<>){print unless(/felixzh1/);}' < file
perl -n -e 'print unless(/felixzh1/);' < 1.txt >2.txt
 
4.1 在diskinfo的上一行加#add by abc,在其下一行加'print (stderr,"abc line111 \n")',
#!/usr/bin/perl
my $dist = 'diskinfo';
while (<DATA>) {
    print /$dist/
      ? ( "#add by abc\n", $_, 'print (stderr,"abc line111 \n")', "\n" )
      : $_;
}
__DATA__
fdfa
sort_diskinfo()
print1
# perl -lape '$_="#add by abc\n$_\nprint (stderr,\"abc line111\\n\")" if /diskinfo/' 1.txt
(la即lane可以实验去掉看看) 

example 5: simulate grep- leave key word lines
#!/usr/bin/perl
#p1 is filename , p2 is begin number, p3 is end number
$file=$ARGV[0];
#$begin = $ARGV[1];
#$end = $ARGV[2];

#system(perl -ne 'print if $begin..$end' $file >1.txt);
$s1="out";
$output = $file.$s1;

open($fh,'<',$file) or die $!;
open($fhout,">$output");

while ($line=<$fh>)
{
        @tmp = split(/ /,$line);
        @tmp1 = split(/-/,$tmp[0]);

        if ( $tmp1[0] == 2017 )
        {
                $mLineFlag =0;
                #multiple regular condition ,use |
                if ($line =~ (/H323Proxy|SIGNAL|MC/) )
                {
                $mLineFlag =1;
                print $fhout $line;
                }
        }
        else
        {
                if ($mLineFlag)
                {
                print $fhout $line;
                }
        }
}
close $fh;
close $fhout;

example 6:use hash to find dup
#!/usr/bin/perl -w
$direct=$ARGV[0];
system ("sh /home/fzhao/txt/1.sh $direct");
$count=0;
$dup=0;
$all=0;
$len=0;
@b=();
%hash;

open my $fh , '<' ,'1';
open my $fh2 , '>>' ,'11';
while (my $line=<$fh>) {
    @array =split (/\s+/,$line);
    if ( $direct==0 )
     {
          $hsRas=$array[14];
     }
    else
    {
          $hsRas=$array[15];
    }

    $all++;
    $flag=0;
    $key=0;
    for $key (keys %hash)
    {
         if ( $key eq  $hsRas )
         {
            $dup++;
            $flag=1;
            last;
         }
    }
    $hash{$key} =1;
    if ( $flag == 0)
    {
        print $fh2 "$hsRas\n";
        $count++;
    }
}

close ($fh);
close ($fh2);
print "all=$all;dup=$dup;count=$count \n";

example 7: class

文本:

$ cat 9.txt
abrt-action-analyze-backtrace
abrt-action-analyze-c
abrt-action-analyze-core
abrt-action-analyze-oops
abrt-action-analyze-python
abrt-action-generate-backtrace
abrt-action-install-debuginfo
abrt-action-list-dsos
abrt-action-save-package-data
abrt-action-trim-files
abrt-applet

例子分析

#!/opt/exp/bin/perl -w
use strict;
my $file=$ARGV[0];
my $line;
my @tmp;
my $fh;
my %uniq;
my @list;
open($fh,'<',$file) or die $!;
print "line6:$file \n";
while ($line=<$fh>) {
        print "line8:$line ";
      #don;t need add \n, because perl read each line include "\n"
       print "line9:$_ \n";
      #string or list change to array
     # error1 @tmp=$line ,数组将仅有一个元素. @tmp = split(/-/,$line);数组将存line分割出来的各个元素
       @tmp = split(/-/,$line);
     #输出数组
       print "line10:@tmp \n";
     # print 最后元素(从最后向前print 元素)
       print "line11:$tmp[-1];$tmp[-2];$tmp[-3] \n";
        #不会匹配第一个“- ”,因为有$限制
        $line =~ s/-([^-]+)$//;
        print "line12:$line \n";
      #将每行的值放入数组保持
        push @list, $line;
}

#grep 当成一个循环, uniq{$_} 为0,取反为1,为1则放入list中,为0则不放入;

# uniq 是一个哈希.哈希可以将string做为下标.   然后$uniq{$_}++;这样去掉了重复的行

# sort 按字母排序

my @output = sort(grep {!$uniq{$_}++} @list);

# 因为在$line =~ s/-([^-]+)$//;此处,string的\n也被用空替换了,所以各个数组元素之间,要加上\n区别开

# join 返回值是string ,将数组变成了带\n的一个string

print join("\n", @output);

===================

example 8:

$ cat 10.txt
wang 12 qian 45 67 sun 22
31 tang 77 89 43 li
nan 78
将数字乘以2
$ cat number.pl
#!/opt/exp/bin/perl -w
my $file = $ARGV[0];
my @tmp;
my $fh;
my $i;
open ($fh,'<',$file) or die $!;
while (my $line=<$fh>) {
       @tmp = split(/\s+/, $line);
       print "line6:@tmp";
#在正则中e表示执行函数,此句表示将数字用函数运算的结果,替换
        $line =~ s/(\d+)/$1*2/eg;
          print "line16:$line \n";
}
example 9:
 perl  批量更改文件名
[root@localhost test]# ls *.txt
a.txt  b.txt
[root@localhost test]# perl -e 'foreach(<*.txt>) {s/.txt$//;rename(qq{$_.txt},qq{$_-2011.txt})}'-------------------此处s/.txt$// 获取文件除去后缀名的文件名a,b
[root@localhost test]# ls *.txt
a-2011.txt  b-2011.txt
简单注释:如果文件名放到运算符(<>)中,perl会自动支持globbing。glob函数与运算符<*>点作用是完全相同的。
[root@localhost test]# perl -e 'foreach(glob("*.txt")) {s/.txt$//;rename(qq{$_.txt},qq{$_-2011.txt})}'
[root@localhost test]# ls *.txt
a-2011-2011.txt  b-2011-2011.txt
 
example 10:  删除某行,删除一行
方法1:
perl -ne 'print  if ! /^sky/' record.txt
        chihao        22        secret        提交        
        alien        25        male        提交        
       sky        20        secret        提交 
方法2:
$ perl -we '
use strict;
open(FN,"test.txt");
while(<FN>){
  next if /\&test/;
  print;
}
方法3:
open(FILE,"<a.txt"); 
@text=<FILE>;
open(FILL,">b.txt")
for(my $i=0; $i < @text; $i++)
{ 
if($text[$i] !~/bug/){
print FILL $text[$i];
} 
}
close FILL;
close FILE;
如果是空行,直接将$text[$i] !~/bug/ 替换成 $text[$i] eq ""
 
example 11:
<*> 应该是glob,类似shell里面ls所有的文件
print <> ;   cat 的perl实现,
print sort <> ; sort的perl实现
正则 ^但是使用表示行首,^.后接字符表示以该字符开头
example12:   perl eval
类似java中的try{}catch{} 语句,perl中也可以捕获程序执行过程中的异常,防止因为局部异常导致程序全盘退出。
       my $a=0;
      my $b=1;
      my $c=1;
    eval {
        $c = $b/$a;
       };
        print "An error occurred:$@" if $@
      $@ 存放正常,异常的info
        注意与shell 中eval的区别
foo=10
x=foo
eval y=’$’$x
echo $y

eval可读取一连串的参数,然后再依参数本身的特性来执行

参数不限数目,彼此之间用分号分开。
那么eval y='$'$x 等同与 eval y="$"$x
‘ ’ ,或“ ” 的作用是 告诉shell,有两个参数需要展开。
第一次取参数时候,将$x 展开,得到foo,此时表达式可以理解为 y=$foo
那么第二次在展开时候,就会对$foo 展开,那么就得到了10

example14: perl在制定行前添加一行

<p style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;"></p><pre name="code" class="html">#!/opt/exp/bin/perl -w
foreach my $file (glob "*.tcl") {
        print "$file\n";
        &max($file);
}
sub max {
        my $dist = 'WISEopt';
        my $line = 0;
        my $i = 0;
        my $f1 = shift @_;
        my $f2 = $f1.".bak";
        my $fd;
        my $fd2;
        open $fd, "<$f1";
        open $fd2, ">$f2";
        while (<$fd>) {
                $i = $i +1;
                $line = $i;
                print $fd2 /$dist/
                ? ( "exec echo \"felixzh1 $line C(RCS\${rcs}WISEopt)=\$C(RCS\${r
cs}WISEopt)>>/bld/felixzh/1\n\"", $_,"\n")
                : $_;
        }
        close $fd;
        close $fd2;
}

example15: 用perl排序sort:

my @array = (100,5,8,92,-7,34,29,58,8,10,24);
my @sorted_array = sort { $a <=> $b } @array;
#sort { $a <=> $b } @array;就是子函数if {} else{} 。


    my @data = qw(a1 b4 c123 d328 z32 m10);
    #提出数字部分
    my @data_with_num_part;
    for (@data) {
        die "$_ don't have num part" unless $_ =~ /(\d+)/;
        push @data_with_num_part, [$_, $1]; #将文本和它的数字部分打包成一个数组
    }
    
    @temp=sort { $a->[1] <=> $b->[1]} @data_with_num_part;
    # 对数字部分排序,然后用 map 取出原文本
    my @sorted = map $_->[0] , @temp;
    #@temp is hash array, [$_,$1]
   # foreach (@temp) {
    #    push @sort ,$_->[0];
   # }
exmaple 16 compare apache lib-simulate grep -search A.txt lib in B.txt
#!/usr/bin/perl -w
my $file=$ARGV[0];
my $file1=$ARGV[1];
$file2 ="found.txt";
$file3 ="nofound.txt";
open($fh,'<',$file) or die $!;
open($fh1,'<',$file1) or die $!;
open($fh2,'>',$file2) or die $!;
open($fh3,'>',$file3) or die $!;
my @list="";
$j=0;
while ($line=<$fh>) {
        if ($line =~ /.*\\(mod.*)/)
        {
                $a=$1;
                #######################################
                #consult don;t add \n ,all array list print in one line??????????????
                $a=$a."\n";
                push (@list ,$a);
                $j++;
                #can;t use print @list to print array
                #foreach(@list)
                #{
                #       print "line16:$_\n";
                #}
        }
}

while ($line1=<$fh1>) {
        push @list1 ,$line1;
}

$found=0;
$nofound=0;

my @found1="";
my @nofound1="";

$ii=0;
print @list;

foreach (@list)
{
        $ii++;
        $a = $_;

        if ( $a eq "" )
        {
                next;
        }
        #success use grep , key is use (),otherwise it don;t get element ,it get all array
        @f= (grep  /$a/,  @list1);
        if (@f)
        {
                $found++;
                push (@found1,$a);
                print $fh2 $a;
        }
        else
        {
        #attention    print "line27:$a \n"; the space will also been printed.
                $nofound++;
                push @nofound1 ,$a;
                print $fh3 $a;
        }
}
my $aa=@found1;
my $bb=@nofound1;
print "found=$found;nofound=$nofound;$aa;$bb\n";
print ("@found1");
print ("@nofound1");

eg 16 提取指定行之间的内容再正则过滤掉内容

perl -ne 'print if 8..12
先提取指定范围的内容

#!/usr/bin/perl
open($fh,'<',"1.txt") or die $!;
open($fhout,">2.txt");

while ($line=<$fh>)
{
        @tmp = split(/ /,$line);
        @tmp1 = split(/-/,$tmp[0]);


        if ( $tmp1[0] == 2017 )
        {
                $mLineFlag =0;
                //multiple regular condition ,use |
                if ($line =~ (/H323Proxy|SIGNAL|MC/) )
                {
                $mLineFlag =1;
                print $fhout $line;
                }
        }
        else
        {
                if ($mLineFlag)
                {
                print $fhout $line;
                }
        }
}
close $fh;
close $fhout;

eg17  不重复数据字段统计

#!/usr/bin/perl -w
$direct=$ARGV[0];  //read perl pamameter 1
system ("sh /home/fzhao/txt/1.sh $direct");  //perl call shell
$count=0;
$dup=0;
$all=0;
$len=0;
@b=();

open my $fh , '<' ,'1';
open my $fh2 , '>>' ,'11';
while (my $line=<$fh>) {
    @array =split (/\s+/,$line);  //split line into field
=pod                                       //perl 成段注释方法
    if ($first==0)
    {
       print "@array";
       print "\n";
       foreach (@array)
       {
          print $_;
          print ";;";
       }
       $first=1;
       exit;
    }
=cut
    if ( $direct==0 )
     {
          $hsRas=$array[14];
     }
    else
    {
          $hsRas=$array[15];
    }
    $all++;
    $flag=0;
    foreach (@b)   //遍历数组
    {
         if ( $_ eq  $hsRas )
         {
            $dup++;
            $flag=1;
            last;
         }
    }
    push @b , $hsRas;
    $len =@b;
    if ( $flag == 0)
    {
        print $fh2 "$hsRas\n";
        $count++;
    }
#   print "hsRas=$hsRas\n";
}

close ($fh);
close ($fh2);
print "all=$all;dup=$dup;count=$count \n";

17 在行后加空行or删除空行

文本间隔
# 在每一行后面增加一空行
思路:将最后的\n换成space+\n 输出
#!/opt/exp/bin/perl
$^I=".bak";
while (<>) {
        chomp($_);
        print "$_ \n";
}
# 将原来的所有空行删除并在每一行后面增加一空行。
# 这样在输出的文本中每一行后面将有且只有一空行
思路:读取每一行,如果空行不输出,如果是非空行,输出然后在打印一个空行
#!/opt/exp/bin/perl
$^I=".bak";
while (<>) {
   if (/^\b*$/) {
       next;
   } else {
       print "$_";
       print "\n";
   }
}
# 在每一行后面增加两行空行
思路:读取每一行,之后加两个print \n
#!/opt/exp/bin/perl
$^I=".bak";
while (<>) {
   print "$_";
   print "\n";
   print "\n";
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值