#!/usr/bin/perl
#########################################################################
# file name: vifind.pl #
# vi specific files by pattern in current folder #
# use $MYEDITOR to open file, if no suce variable was found, use vi/vim #
# use profile $VIMRC to load user vi profile #
#########################################################################
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;
}
}
# check whether there's user defined editor
my $vi = $ENV{"MYEDITOR"};
{
# if no user defined editor, use vim
$vi = `which vim` if($vi eq "");
# if no vim was found, use vi
$vi = `which vi` if($vi eq "");
die "No editor was found in $ENV{'PATH'}/n" if($vi eq "");
}
# remove carriage
chomp($vi);
# check user defined vimrc file
my $editor = `basename $vi`;
chomp($editor);
my $vimrc = $ENV{"VIMRC"};
chomp($vimrc);
if(($editor eq "vi" or $editor eq "vim") and $vimrc ne ""){
$vi = $vi . " -u $vimrc"
}
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";
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 = "$vi $menu[1]";
}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 = "$vi $menu[$line]";
}
}
print "$cmd/n";
system("$cmd");
exit 0
vifind
最新推荐文章于 2023-07-26 06:00:00 发布