Quantcast
Channel: Hone Watson Bookmarks » Ubuntu Intrepid Ibex
Viewing all articles
Browse latest Browse all 4

Linux Command Line “Search and Replace” Text in Files Recursively “Find and Replace” Grep Sed Python Regex Regular Expression

$
0
0

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
.



Viewing all articles
Browse latest Browse all 4

Trending Articles