Find and replace a particular term in multiple files
sed -i.bak 's/searchword/replaceword/g' file*.txt
# Or sed -i.bak '/searchword/s/searchword/replaceword/g' file*.txt
With bash 4.0, you can do recursive search for files
#!/bin/bash
shopt -s globstar
for file in **/file*.txt
do
sed -i.bak 's/searchword/replaceword/g' $file
# or sed -i.bak '/searchword/s/searchword/replaceword/g' $file
done
Or with GNU find
find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;
How to replace a string in multiple files in linux command line
cd /path/to/your/folder
sed -i 's/foo/bar/g' *
Occurrences of "foo" will be replaced with "bar".
On BSD systems like macOS, you need to provide a backup extension like -i '.bak'
or else "risk corruption or partial content" per the manpage.
cd /path/to/your/folder
sed -i '.bak' 's/foo/bar/g' *
find and replace in multiple files on command line
there are many ways .But one of the answers would be:
find . -name '*.html' |xargs perl -pi -e 's/find/replace/g'
Finding and replacing text in multiple files within a folder
Cleaned up:
Sub ProcessFiles()
Dim wordApp As Word.Application
Dim wdDoc As Word.document
Dim strPath As String, allfiles As Collection, fPath
strPath = GetFolderPath()
If Len(strPath) = 0 Then Exit Sub
Set allfiles = GetAllFiles(strPath, "*.doc*")
If allfiles.Count = 0 Then
MsgBox "No Word files found"
Exit Sub
End If
Set wordApp = New Word.Application
wordApp.Visible = True
'loop over found files
For Each fPath In allfiles
Debug.Print "Processing " & fPath
Set wdDoc = wordApp.documents.Open(fPath)
ReplaceDocContent wdDoc, ".", " "
ReplaceDocContent wdDoc, ",", " "
ReplaceDocContent wdDoc, "~", " "
'etc.....
wdDoc.Close True 'close and save changes
Next fPath
MsgBox "done"
End Sub
'replace text in a Word document with some other text
Private Sub ReplaceDocContent(doc As Word.document, findWhat, replaceWith)
With doc.Range.Find
.Text = findWhat
.Replacement.Text = replaceWith
.Execute Replace:=wdReplaceAll
End With
End Sub
'collect all files under folder `strPath` which match `pattern`
Private Function GetAllFiles(ByVal strPath As String, pattern As String) As Collection
Dim objFile As Object, col As New Collection
'Create an instance of the FileSystemObject and list all files
For Each objFile In CreateObject("Scripting.FileSystemObject").GetFolder(strPath).Files
If objFile.Path Like pattern Then col.Add objFile.Path
Next objFile
Set GetAllFiles = col
End Function
'return selected folder path or empty string
Function GetFolderPath() As String
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show <> 0 Then GetFolderPath = .SelectedItems(1)
End With
End Function
find and replace strings in files in a particular directory
You can use the sed
expression:
sed 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g'
And add it into a find
command to check .h
, .cpp
and .hpp
files (idea coming from List files with certain extensions with ls and grep):
find . -iregex '.*\.\(h\|cpp\|hpp\)'
All together:
find . -iregex '.*\.\(h\|cpp\|hpp\)' -exec sed -i.bak 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' {} \;
Note the usage of sed -i.bak
in order to to edits in place but create a file.bak
backup file.
Variable pattern
If your pattern varies, you can use:
sed -r '/^throw/s/throw (.*);$/throw CreateException(\1);/' file
This does the replacement in the lines starting with throw
. It catches everything after throw
up to ;
and prints it back surrounded by CreateException();`.
Test
$ cat a.hpp
throw some::lengthy::exception();
throw you();
asdfasdf throw you();
$ sed -r '/^throw/s/throw (.*);$/throw CreateException(\1);/' a.hpp
throw CreateException(some::lengthy::exception());
throw CreateException(you());
asdfasdf throw you();
Find and replace a string within multiple files contained within a directory using a .bat file
You probably want [SS64]: FOR /R.
Small example:
script00.bat:
@echo off
setlocal enableextensions disabledelayedexpansion
set _ROOT_DIR=".\dir0"
for /R %_ROOT_DIR% %%f in (*.config) do (
echo file: %%f
rem Do the rest
)
Output:
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q068684288]> tree /f /a
Folder PATH listing for volume SSD0-WORK
Volume serial number is AE9E-72AC
E:.
| script00.bat
|
\---dir0
+---dir0
| file.config
|
+---dir1
| file.config
|
\---dir2
file.config
[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q068684288]> script00.bat
file: e:\Work\Dev\StackOverflow\q068684288\dir0\dir0\file.config
file: e:\Work\Dev\StackOverflow\q068684288\dir0\dir1\file.config
file: e:\Work\Dev\StackOverflow\q068684288\dir0\dir2\file.config
find and replace string from multiple files in a folder using python
Here's a solution using os, glob and ntpath. The results are saved in a directory called "output". You need to put this in the directory where you have the .c and .h files and run it.
Create a separate directory called output and put the edited files there:
import glob
import ntpath
import os
output_dir = "output"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for f in glob.glob("*.[ch]"):
with open(f, 'r') as inputfile:
with open('%s/%s' % (output_dir, ntpath.basename(f)), 'w') as outputfile:
for line in inputfile:
outputfile.write(line.replace('Version1', 'Version2.2.1'))
Replace strings in place:
IMPORTANT! Please make sure to back up your files before running this:
import glob
for f in glob.glob("*.[ch]"):
with open(f, "r") as inputfile:
newText = inputfile.read().replace('Version1', 'Version2.2.1')
with open(f, "w") as outputfile:
outputfile.write(newText)
Replacing a String In Multiple Files With Their Filename
Something like this?
Get-ChildItem -Filter "*.txt" | ForEach-Object {
$Path=$_.FullName; (Get-Content $Path) -replace 'unamed', $_.BaseName | Set-Content $Path
}
Related Topics
Match a String That Contains a Newline Using Sed
How to Find Words from One File in Another File
What Are Good Linux/Unix Books for an Advancing User
Linux Kernel Device Driver to Dma from a Device into User-Space Memory
How to Append the Output to a File
Is There a Limit on Number of Tcp/Ip Connections Between MAChines on Linux
Unix: Differencebetween Source and Export
Linux Tool to Send Raw Data to a Tcp Server
How to Convert Pptx Files to Jpg or Png (For Each Slide) on Linux
How to Query X11 Display Resolution
How to Capture Still Image from Webcam on Linux
Vagrant Synced Folders Not Working Real-Time on Virtualbox
How to Move a Relative Symbolic Link
Scp File from Local to Heroku Server
Minimizing Copies When Writing Large Data to a Socket
How to Specify an Icon with a Relative Path for a Linux Desktop Entry File