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

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

WBOY
Release: 2016-06-08 17:27:59
Original
1000 people have browsed it
<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! ";
}
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template