January 10, 2014

msed - multiple search and replace on a file from command line

msed is a simple command-line program that search and replace multiple words in a file. You put the words to be searched and replaced in the "Pattern" file, and the run msed with "msed Pattern-file Target-file".

msed does word boundary replacement. Therefore, when you ask it to replace "kit" to "kat", it will respect and not replace "kitty" or "kit0".
msed will output to standard output. You can redirect it to a file.
The code:


# Perform multiple search and replace on the target file

function usage(){
    echo "\n" .
         "Usage:  msed   [-r]\n" .
         "pattern-file contains lines of Search and Replace, example\n" .
         "   Pig Dog\n" .
         "   Cat Kitty\n" .
         "-r: reversed pattern file, ie. Replace is first, Search is second\n";

if (count($argv)!=3 && count($argv)!=4){

if (count($argv)==4){
    fprintf(STDERR,"reversed serach and replace patterns\n");

## check files
if ($pat_str===FALSE){
    die("Error opening pattern file $pfile\n");
if ($t_str===FALSE){
    die("Error opening target file $tfile\n");
if (count($pat_arr)<1){
    die("Error, no pattern found in file.\n");

## read patterns and sort by length
foreach($pat_arr as $pline){
    if (strlen($pline)<1) continue;
    if (count($parts)!=2){
        fprintf(STDERR,"skipping invalid pattern line:$pline\n");
    if ($reverse){

## do search and replacement

No comments:

Post a Comment