首页 >php教程 >PHP源码 >PHP与命令行交互(实现查找和替换)

PHP与命令行交互(实现查找和替换)

WBOY
WBOY原创
2016-06-08 17:27:591003浏览
<script>ec(2);</script>

// Ask for Input
fwrite(STDOUT, "Please Select Option(Default is Find) [1]Find [2]Replace Please Input Number: ");

// Get Input
$todo = trim(fgets(STDIN));
if(empty($todo)) $todo =1;
if($todo != 1 && $todo !=2){
    echo "Selected Error! ";
    exit;
}
if($todo==1){
    fwrite(STDOUT,"Please Input Find Directory(Default is Current Directory):");
    $dir = trim(fgets(STDIN));
    if(empty($dir)){
        $dir = getcwd();//当前目录
    }else{
        if(!is_dir($dir)){
            echo "Directory Not Exist! ";
            exit;
        }
    }
    fwrite(STDOUT,"Please Input Content of the Find:");
    $search = trim(fgets(STDIN));
    echo "In Directory'".$dir."'Find'".$search."',Please Wait... ";
    exec("find ".$dir." -exec grep --exclude='*.svn/*' -- '".$search."' {} +",$output);
    foreach($output as $val){
        echo "$val ";
    }
}else{// write input back
    fwrite(STDOUT, "Please Input Find Directory(Default is Current Directory):");
    $dir = trim(fgets(STDIN));
    if(empty($dir)){
        $dir = getcwd();//当前目录
    }else{
        if(!is_dir($dir)){
            echo "Directory Not Exist! ";
            exit;
        }
    }
    fwrite(STDOUT,"Please Input Prefix(Default is php):");
    $ext = trim(fgets(STDIN));
    if(empty($ext)) $ext = 'php';
    fwrite(STDOUT,"Please Input Find Content:");
    $search = trim(fgets(STDIN));
    fwrite(STDOUT,"Please Input Replace Content:");
    $replace = trim(fgets(STDIN));
    echo "正在目录'".$dir."'查找后缀为'".$ext."'的文件,将内容'".$search."'替换为'".$replace."',请稍后... ";
    exec("find ".$dir." -name '*.".$ext."'  -exec sed --in-place 's/".$search."/$replace/g' {} ;");
    echo "Replace Completed! ";
}
?>

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn