Skip navigation

I looked at different ways to “Search and Replace” Text in Files Recursively using the Linux Command Line.

“Find and Replace” with grep and sed combinations all sucked so I created this Python script to search through files and folders recursively for text then replace it. This script also creates backups of the files before it does the string replace.

Here is how to use it:


./fnr.py '/path/to_begin/from/' 'string to find' 'string to replace'

The script uses python regex regular expression syntax:


./fnr.py '/path/to_begin/from/' '^Let me tell you a funny .*$' 'Let me tell you a funny story!'

Here is how to set it up:


wget --output-file=fnr.py http://images.honewatson.com/random_files/find_replace_files.py
chmod +x fnr.py

Here is the code:


#!/usr/bin/env python
#search recursively through folders and replace text in files.
import sys, os, re, string, subprocess

argv = sys.argv
base_path = argv[1]
find_string = argv[2]
replace_string = argv[3]

def read_content(the_file):
f = file(the_file, 'r')
content = f.read()
f.close()
return content

def write_content(the_file, content):
f = file(the_file, 'w')
f.write(content)
f.close

def setup_find_results(base_path, find_string, replace_string):
b = subprocess.Popen([r"grep", "-rl", find_string, base_path], stdout=subprocess.PIPE)
for i in b.stdout:
the_file = re.sub('\n', '', i)
if not re.search('\.backup', the_file):
the_file_backup = '%s%s' % (the_file, '.backup')
subprocess.Popen([r"cp", the_file, the_file_backup])
content = read_content(the_file)
content = re.sub(find_string, replace_string, content)
write_content(the_file, content)

setup_find_results(base_path, find_string, replace_string)

Here is the link for the script:

Find and replace text in folder files recursively
.

About these ads

2 Comments

  1. hmm, grep and sed still seem easier!

    for file in `grep -r -l abc *`
    do sed ‘s/abc/xyz/g’ $file > $file.fixed
    echo $file.fixed
    done

  2. I found this oneliner

    find ./ -type f -exec sed -i ‘s/string1/string2/’ {} \;

    on http://gabeanderson.com/2008/02/01/unixlinux-find-replace-in-multiple-files/


2 Trackbacks/Pingbacks

  1. […] in Uncategorized Unlike this overkill solution in python, bash is the best tool for this sort of task. grep and sed are your friends; for file […]

  2. […] in Uncategorized Unlike this overkill solution in python, bash is the best tool for this sort of task. grep and sed are your friends… […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: