#!/usr/bin/perl $USAGE = " USAGE: pedit -s,re,re,opt FILES SYNOPSIS: Substitute strings inline in files. OPTIONS: -s/re/re/gioe Command to execute on each line of files. -Ffilelist List of files and s/// cmd in filelist. -ffilelist List of files in filelist. -xcmdfile Take s/// from cmdfile. -i.bak Extension for old file, default is ~ -q quiet mode, don't show diffs. -v Verbose. -? help. EXAMPLES: o Convert / to comma in file x.c and rename orginal x.c to x.c.bak > pedit -s#/#,#g -i.bak x.c o Filenames are piped. > dir/s/b | pedit -s,mosh,MohsinA,gio o Filenames in file list.txt > pedit -flist.txt -s/x/y/i o Commands and filenames in file xyz. > pedit -Fxyz > cat xyz s/1992/1993/g file1.c file2.h o Format \"column2 column1\" as a table in filetab. > cat cmdfile s:(.*)/([\\w_\\d.]+)\$:sprintf(\"\%-20s\%s\",\$2,\$1):e o Simple use, correct spellings in all h files: > perl -pe s/recieve/receive/gi -i~ *.h o Convert LF to CR LF and Back. > perl -pe \"s,\\n,\\r\\n,g\" -i~ UNIXFILES > perl -pe \"s,\\r\\n,\\n,g\" -i~ DOSFILES NOTES: Will not edit, if backup file exists. AUTHOR: GPL(C), http://www.cs.albany.edu/~mosh "; $verbose = 1; $INPLACE_EDIT = '~'; while( $_ = $ARGV[0], /^-/ ){ shift; if( m/^--$/ ){ last; }elsif( m/^-[Ff](.+)/ ){ $filename = $1; open( FILELIST, "< $filename" ) || die "Cannot read $filename\n"; # -F means first line of file is the s/// command. $op1 = if m/-F/; @filelist = ; @filelist = grep( s/\n//, @filelist ); close FILELIST; print STDERR "From $filename = @ARGV.\n"; }elsif( m/^-q/ ){ $quiet++; print STDERR "quiet mode, editing at your own risk.\n" }elsif( m/^-(s.+)/i ){ $op1 = $1; print STDERR "subst: $op1.\n" }elsif( m/^-v(.*)/ ){ $verbose = $1 || 1; print STDERR "verbose = $verbose.\n" }elsif( m/^-x(.+)/ ){ $cmdfile = $1; open( CMDFILE, "<$cmdfile") || die "Cannot read -xcmdfile $cmdfile\n"; $op1 = ; close( CMDFILE ); print STDERR "cmd=$op1\n"; }elsif( m/^-i(.+)/ ){ print STDERR "INPLACE_EDIT=$^I=$INPLACE_EDIT.\n" if $verbose >= 2; $INPLACE_EDIT = $^I = $1; print STDERR "INPLACE_EDIT=$^I=$INPLACE_EDIT;\n"; }elsif( m/^-\?/ ){ print $USAGE; exit; }else{ die "Invalid option: $_, see -? for help.\n"; } } die "Need args, see -? for help\n" unless $op1; if( @filelist ){ @ARGV = @filelist; }elsif( ! @ARGV ){ @ARGV = ; chop(@ARGV); } print STDERR "subst=$op1 \n ARGV = @ARGV \n" if $verbose; # Filter the files. foreach (@ARGV) { if( -e "$_~" ){ warn "Skipping $_ backup file $_~ exists.\n"; }elsif( ! -f $_ ){ warn "skipping $_, not a file.\n"; }else{ push( @NEWARGV, $_ ); } } die "No files to edit? see -? for help.\n" unless @NEWARGV; @ARGV = @NEWARGV; $lineschanged = 0; while( <> ){ $line = $_; if( eval $op1 ){ $lineschanged++; if( $verbose ){ print STDERR "Changed: $ARGV:$.:\n-$line+$_" unless $quiet; # Changed: FILE:LINE: # -OLD # +NEW } } die $@ if $@; print $_; if( eof ){ print STDERR "Edited $lineschanged/$. lines of $ARGV\n"; $lineschanged=0; close(ARGV); } }