lessfind

#!/usr/bin/perl

#######################################################################
# file name: lessfind                                                 #
# use less to open specific files by pattern in current folder        #
#######################################################################

my $me = `basename $0`;
chomp($me);

sub showHelp{
  print "Usage $me [-dnumber] file-pattern1 [file-pattern2] [...]/n";
  print "-d: search depth/n";
  print "the file pattern is case insensitive/n";
}

my $maxdepth = undef;

if(@ARGV == 0){
  showHelp();
  exit 0;
 
}elsif(@ARGV == 1){
  my $arg1 = $ARGV[0];
  if($arg1 =~ m//-d/d*/){
    showHelp();
    exit 1;
  }
 
}else{
  my $arg1 = $ARGV[0];
  if($arg1 =~ m/^(/-d)(/d+)$/){
    $maxdepth = $2;
  }else{
    showHelp();
    exit 1;
  }
 
}

my %files = ();
my $index = 1;

my $startIndex = defined $maxdepth ? 1 : 0;

# execute find
for($i = $startIndex; $i < @ARGV; $i++){
  my $pattern = $ARGV[$i]; 
 
  my $maxdepthArg = $maxdepth > 0 ? " -maxdepth $maxdepth " : "";
  my $findcmd = "find . $maxdepthArg -xtype f -iname /"*$pattern*/" 2>/dev/null";
#  print "$findcmd/n";
 
  my $filelist = `$findcmd`;
  chomp($filelist);
 
  my @items = split("/n", $filelist);
 
  # add find results
  foreach $item (@items){
    if($files{$item} eq ""){
      $files{$item} = $index++;
    }
  }
}

if($index == 1){
  print "No matched files are found!/n";
  exit 0;
}

my @menu = ("exit");

foreach $file (keys(%files)){
  my $key = $file;
  my $no = $files{$key};

  $menu[$no] = $key;
}

# if only one hit, open it by default
my $cmd;
if($#menu == 1){
  $cmd = "cat -n $menu[1] | less";
 
}else{
  # display menu
  for($i = 1; $i < @menu; $i++){
    print "$i. $menu[$i]/n";
  }
  print "0. $menu[0]/n";
  print "input file no:";
 
  # waiting user input
  my $line = <STDIN>;
  chomp($line);
 
  # open file
  if($line =~ m/[0-9]/ && $line > 0 && $line < @menu){
    $cmd = "cat -n $menu[$line] | less";
  }
}

print "$cmd/n";
system("$cmd");

exit 0

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值