Search and Replace Text in Files
Posted: 31 Mar 2017 17:24
Is this possible with anything built into the application?
Forum for XYplorer Users and Developers
https://www.xyplorer.com/xyfc/
Code: Select all
$safe = <<<>>>
txt
xml
xys
nfo
<extend me if necessary!>
>>>;
$search = input("Enter search term...", , , "m");
end (!$search), "Empty search terms are not accepted!";
$replace = input("Enter text to replace with...", , , "m");
$notSafe = "";
$replaced = "";
$notReplaced = "";
foreach($item, <get SelectedItemsPathNames |>, , "e") {
$ext = gpc($item, "ext");
if (!regexmatches($safe, "^$ext$")) {
$notSafe = $notSafe . ((!$notSafe) ? "<crlf>Items with invalid file extension(s)<crlf>$item" : "<crlf>$item" );
continue;
}
$oldContent = readfile($item);
$newContent = replace($oldContent, $search, $replace);
if ($oldContent != $newContent) {
writefile($item, $newContent);
$replaced = $replaced . ((!$replaced) ? "<crlf>Files with replacement(s)<crlf>$item" : "<crlf>$item" );
} else {
$notReplaced = $notReplaced . ((!$notReplaced) ? "<crlf>Files without replacement(s)<crlf>$item" : "<crlf>$item" );
}
}
$result = $notSafe . <crlf> . $replaced . <crlf> . $notReplaced;
text $result;
Code: Select all
$safe = <<<>>>
txt
xml
xys
nfo
<extend me if necessary!>
>>>;
$search = input("Enter search term...", , , "m");
end (!$search), "Empty search terms are not accepted!";
$notSafe = "";
$found = "";
$notFound = "";
foreach($item, <get SelectedItemsPathNames |>, , "e") {
$ext = gpc($item, "ext");
if (!regexmatches($safe, "^$ext$")) {
$notSafe = $notSafe . ((!$notSafe) ? "<crlf>Items with invalid file extension(s)<crlf>$item" : "<crlf>$item" );
continue;
}
if (strpos(readfile($item), $search) != -1) {
$found .= ((!$found) ? "<crlf>File(s) with matching search term<crlf>$item" : "<crlf>$item" );
} else {
$notFound .= ((!$notFound) ? "<crlf>File(s) without matching search term<crlf>$item" : "<crlf>$item" );
}
}
$result = $notSafe . <crlf> . $found . <crlf> . $notFound;
text $result;
tab() and paperfolder()...FileLocator Pro can do this (https://www.mythicsoft.com/filelocatorpro/).I've taken part of your script to do a simple search and replace on one xml file. This is the code:
Code: Select all
$config = "C:\configx.xml";
$search = bookMarkMargin="hide";
$replace = bookMarkMargin="show";
$oldContent = readfile($config);
$newContent = replace($oldContent, $search, $replace);
writefile($config, $newContent);