[X-Unix] Expression/script edit series of txt files in separate subdirectories

Cloyce D. Spradling cloyce+xunix at headgear.org
Tue Aug 16 14:22:52 PDT 2005


On Tue, Aug 16, 2005 at 03:59:37PM -0400, Andrew Kappy wrote:

: I've been trying to construct expressions (or shell scripts) that  
: would go through all of the mailto files and change:
: 1) find all cases of "x" and change to "y"
: 2) add a line with "x" to all
: 3) remove "x" from all files

Assuming that you don't have paths with spaces in them, some variation of
the below will cover that:

  find . -name mailto -print | xargs perl -pi -e 's/YYYY/ZZZZ/g;'

That'd handle #1.  #2 can also easily be accomplished without the aid of
perl, but even with perl it's not too hard:

  find . -name mailto -print | xargs perl -pi -e 'END { print "YYYY\n"; }'

Change the "END" to "BEGIN" to put the new line at the front of the file.

#3 is also easiest with Perl, though this form may not be the most intuitive:

  find . -name mailto -print | xargs perl -pi -e 'next if /YYYY/;'

Some explanation is probably in order.  For perl (this is all in perlrun,
BTW; type 'perldoc perlrun'), the '-p' says to loop over the input lines,
and to print them by default.  The '-i' says to do an in-place edit of files
given on the command line, and '-e' indicates that the following argument is
the text of a script and not the filename of a file containing a script.

The 'find' finds all of your files named 'mailto' and prints their paths,
and xargs takes as many as possible and tacks them onto the end of its
arguments (which in this case is "perl ...").

You can also string all of the above into one command; just combine the text
of the perl scripts, as in:


  find . -name mailto -print | xargs perl -pi -e 'next if /WWWW/; s/YYYY/ZZZZ/g; END { print "TTTTT\n"; }'

If it starts to get too complicated, it's probably best to put the perl script
into a file and just use perl to run it:

  find . -name mailto -print | xargs perl -pi fix_mailto

(assuming you've called it fix_mailto, of course)

--
Cloyce


More information about the X-Unix mailing list