#!/local/bin/php -q */ function SearchLineInFile($infile, $old) { echo " Replace String (Arg3) was empty, ..... we will just list the lines with string = $old ... \n\n"; $i = 0; $changes = 0; if (file_exists($infile)) { $fp = fopen($infile, "r"); if ($fp > 0) { // read the file in while (!feof($fp)) { $buf = fgets($fp, 128); if(eregi($old, $buf)) { echo "Found $new on line $i"; $changes++; } $i++; } } fclose($fp); echo "\nFound $changes occurences of search string\n"; } else echo "\nWARNING: The file '$infile' does NOT exist !\n"; } function ChangeLineInFile($infile, $old, $new) { echo(" Search String is: $old\n"); if (!$new) echo " Replace String (Arg3) was empty, ..... we will just list the lines with string = $old ... \n\n"; else echo " Replace String (Arg3) is: $new\n\n"; $i = 0; $changes = 0; if (file_exists($infile)) { $fp = fopen($infile, "r"); if ($fp > 0) { // read the file in while (!feof($fp)) { $buf = fgets($fp, 128); if(eregi($old, $buf)) { // replace the matched line // $output[$i] = $new; $output[$i] = eregi_replace ($old, $new, $buf); $changes++; } else { // or write the same line $output[$i] = $buf; } $i++; } fclose($fp); echo "\nFound $changes occurences of search string\n"; if ($new) { $fp = @fopen($infile, "w"); if ($fp > 0) { // spit out the array for ($n = 0; $n < $i; $n++) { // echo $output[$n]; fputs($fp, $output[$n]); } fclose($fp); echo "\nMade ALL requested changes, let's hope they are ok !\n"; } } } } else echo "\nWARNING: The file '$infile' does NOT exist !\n"; } function usage ($user_input) { echo (" I got: $user_input\n "); echo ("Usage: SEARCH: replace file-name string REPLACE: replace file-name string replace \n\n"); } echo "\n\nPHP replace program\n*******************\n"; if ( isset($argv[1]) == 0 ) { $input = $argv[1]; usage ($input); exit; } else $infile = $argv[1]; if ( isset($argv[2]) == 0 ) { $input = $argv[1] . " " . $argv[2] ; usage ($input); exit; } else $old = $argv[2]; if ( isset($argv[3]) == 0 ) { $new = FALSE; ChangeLineInFile($infile, $old, $new); } else { $new = $argv[3]; ChangeLineInFile($infile, $old, $new); } ?>