Terminal: Search and Replace text in all files in a folder and its subfolders

I just stumbled across a neat idea using perl to replace the content in files

To replace all occurances of a string:

find ./ -name “*.txt” | xargs perl -pi -e ‘s/stringtoreplace/replacementstring/g’

for every of these examples you can also use sed

find ./ -name “*.txt” | xargs sed -i ‘s/stringtoreplace/replacementstring/’

or rpl

rpl stringtoreplace “replacementstring” ./

or numeros other solutions …

To replace the first occurance:
find /your/home/dir -name “*.txt” | xargs perl -pi -e ‘s/stringtoreplace/replacementstring/’

To replace all files in a folder:
for arg in ls -C1; do perl -pi -e ‘s/stringtoreplace/replacementstring/g’; done;

you can do more cool tricks using the for shell command as demonstrated above. you can add more specific searches. However, you might be better off just writing a shell script. Here is an example of the first find:
for arg in find /your/home/dir -name "*.txt" ; do perl -pi -e ‘s/string/replacement/g’ $arg; done;

Related Posts

Better openerp-server init.d script, for ennhanced Monit/d behavior

simple

December 6, 2012

Linux

No Comment

This script was taken from the default distributions openerp-server init.d script and mainly modified for improved Monit/d behavior. The main problem was that sometimes the openerp-server could not be reliable shutdown – as a result a manual kill had been necessary. This should be now addressed with the following script: [crayon-5b4d80e545035649672741/]

Read More

UNIX: Jailkit – jk_init, jk_chrootsh

simple

January 25, 2012

Linux

No Comment

Sometimes you do not want to have users bugging around with your server, but only set up a shell environment where they can work. The answer for Solaris, many Linux distributions, OpenBSD, FreeBSD and MacOSX is plain and simple JailKit. Install it using the package manager of your favorite distribution or download the source from: […]

Read More

Leave a Reply