myvesta/bin/v-replace-in-file
2020-08-02 02:10:01 +02:00

48 lines
963 B
PHP

#!/usr/bin/php
<?php
$current_user=exec('whoami', $output, $return_var);
if ($current_user != 'root') {echo "You must be root to execute this script\n"; exit(1);}
if (isset($argv)) {
if (count($argv)==4) {
$find=$argv[1];
$replace=$argv[2];
$file=$argv[3];
} else {
echo "Usage: v-replace-in-file 'findString' 'replaceString' file\n";
exit(2);
}
}
function fix_backslashes($s) {
$s=str_replace("\\n", "\n", $s);
$s=str_replace("\\r", "\r", $s);
$s=str_replace("\\t", "\t", $s);
return $s;
}
$find=fix_backslashes($find);
$replace=fix_backslashes($replace);
echo "Find: ".$find."\n";
echo "Replace: ".$replace."\n";
echo "File: ".$file."\n";
if (!file_exists($file)) {
echo "ERROR: File not found!\n";
exit(3);
}
$buf=file_get_contents($file);
if (strpos($buf, $find)===false) {
echo "ERROR: String not found!\n";
exit(4);
}
$buf=str_replace($find, $replace, $buf);
$r=file_put_contents($file, $buf);
if ($r) echo "Done.\n";
exit(0);