XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions / Automated file editing

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

While working on this chapter, I encountered another practical use case. I was using an extremely slow network connection across the⟦U+0002⟧Pacific. The network was overloaded; sometimes even echoing RETURN took over a minute. I needed only a few changes to get an important program running, essentially replacing every sysread with read. Using a full-screen editor over that connection was out of the question.

One line performed all the changes:

% perl -­p -­i -­e '⟦U+001F⟧s/sysread/read/g'⟦U+001F⟧ datei

This runs the Perl program s/sysread/read/g. Yes, that is the whole program: option -e specifies that the entire program follows as a command-line string. Perl options -­p and -i are also used, and the program processes the specified file. Together, these options apply the substitution to each line, then overwrite the original file with the modified one.

Notice that no explicit input string is specified: construct $var =~ ... is absent. With option -p, Perl applies the program to every line. Using /g ensures that sysread is replaced even when it occurs multiple times on one line.

I could have named multiple files instead of one. Perl would substitute on every line of each file. A single command can thus change many files quickly. Only Perl supports this particular command so concisely, but the broader lesson is that regexes in scripting languages are powerful even in small doses.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top