If PowerShell is an option, the function defined below can be used to perform find and replace across files. For example, to find 'a string'
in text files in the current directory, you would do:
dir *.txt | FindReplace 'a string'
To replace 'a string'
with another value, just add the new value at the end:
dir *.txt | FindReplace 'a string' 'replacement string'
You can also call it on a single file using FindReplace -path MyFile.txt 'a string'
.
function FindReplace( [string]$search, [string]$replace, [string[]]$path ) {
# Include paths from pipeline input.
$path += @($input)
# Find all matches in the specified files.
$matches = Select-String -path $path -pattern $search -simpleMatch
# If replacement value was given, perform replacements.
if( $replace ) {
# Group matches by file path.
$matches | group -property Path | % {
$content = Get-Content $_.Name
# Replace all matching lines in current file.
foreach( $match in $_.Group ) {
$index = $match.LineNumber - 1
$line = $content[$index]
$updatedLine = $line -replace $search,$replace
$content[$index] = $updatedLine
# Update match with new line value.
$match | Add-Member NoteProperty UpdatedLine $updatedLine
}
# Update file content.
Set-Content $_.Name $content
}
}
# Return matches.
$matches
}
Note that Select-String
also supports regex matches, but has been constrainted to simple matches for simplicity ;) You can also perform a more robust replacement like Jon suggested, rather than just overwriting the file with the new content.