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

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

WBOY
WBOY原創
2016-06-08 17:27:591002瀏覽
<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