Subject: substitute delimited words

From: Ed Kubaitis - CCSO <[email-masked]>
Date: Sun, 25 Apr 1993 13:13:48 -0400

Here's a script that uses the sam command pipe to save keystrokes when
substituting delimited words.                                              

Ed
==============================================================================
#! /usr/local/bin/perl
#
#   sam_sw - generate sam command to substitute delimited words
#
#   usage: !sam_sw [-X] [-,] from to

while($_ = $ARGV[0], /^-/) {
   shift;
   if    (m!^-X$!) { $XFlag++; $CommaFlag++; }
   elsif (m!^-,$!) { $CommaFlag++; }
   else            { &usage; }
   }
($from,$to, @toomany) = @ARGV;
&usage if @toomany || !$from || !$to;

$command = "X " if $XFlag;
$command .= "," if $CommaFlag;
$from =~ s/([()*[\]\\^\$+?!])/\\$1/g; # escape meta characters
$to =~ s/([()*[\]\\^\$+?!])/\\$1/g;
$command .= "s!(^|[^A-Za-z0-9_])$from(\$|[^A-Za-z0-9_])!\\1$to\\2!g\n";
&sampipe($command);

sub sampipe {
   local($commands) = @_;

   $user = $ENV{'USER'};
   $user = $ENV{'LOGNAME'} unless $user;
   $user || die "$0: no USER or LOGNAME environment variable.\n";

   $pipe = ".sam.$user";
   $pipe .= ".$ENV{'DISPLAY'}" if $ENV{'DISPLAY'};

   $Pipe = "/tmp/$pipe";
   $Pipe = "/usr/tmp/$pipe" unless -p $Pipe;
   -p $Pipe || die "$0: no sam pipe($pipe) in /tmp or /usr/tmp\n";

   open(Pipe, ">$Pipe") || die "$0: $Pipe: $!\n";
   print Pipe "$commands";
   close(Pipe);
   }

sub usage { die "usage: !sam_sw [-X] [-,] from to\n"; }