How to search and replace text in a file?
fileinput
already supports inplace editing. It redirects stdout
to the file in this case:
#!/usr/bin/env python3
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')
Find and Replace Inside a Text File from a Bash Command
The easiest way is to use sed (or perl):
sed -i -e 's/abc/XYZ/g' /tmp/file.txt
Which will invoke sed to do an in-place edit due to the -i
option. This can be called from bash.
If you really really want to use just bash, then the following can work:
while IFS='' read -r a; do
echo "${a//abc/XYZ}"
done < /tmp/file.txt > /tmp/file.txt.t
mv /tmp/file.txt{.t,}
This loops over each line, doing a substitution, and writing to a temporary file (don't want to clobber the input). The move at the end just moves temporary to the original name. (For robustness and security, the temporary file name should not be static or predictable, but let's not go there.)
For Mac users:
sed -i '' 's/abc/XYZ/g' /tmp/file.txt
(See the comment below why)
Replacing strings with variables inside file in Python
You can use the .format
method.
You can use **
to pass it a dictionary containing the variable.
Therefore you can use the locals()
or globals()
, which are dictionary of all the locals and globals variables.
e.g.
text = text.format(**globals())
Complete code:
my_var="this"
some_var="that"
for file in ["file1.md", "file2.md"]:
with open(file, "r") as f:
text = f.read()
text = text.format(**globals())
print(text)
Replace a string in a file with contents copied from another file
If I have properly understood your question, the following should do the trick:
#!/bin/bash
fileToBeRead="key.txt" #Whatever
var=$(tr -d '[:blank:]\n' < $fileToBeRead)
sed -i "s#sdkPrivateKey=\"\"#sdkUniqueKey=\"$var\"#g" AppConstants.txt
Since the key contains backslashes/slashes you should use a different separator for sed (e.g. #) or the sentence will be misparsed.
EDIT:
KEY="$var" perl -pi -e 's/sdkPrivateKey=""/sdkUniqueKey="$ENV{KEY}"/g' AppConstants.txt
perl
can be used instead of sed
in order to avoid sed
's separator issues. Check out @DennisWilliamson's comment below.
How can you find and replace text in a file using the Windows command-line environment?
A lot of the answers here helped point me in the right direction, however none were suitable for me, so I am posting my solution.
I have Windows 7, which comes with PowerShell built-in. Here is the script I used to find/replace all instances of text in a file:
powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt"
To explain it:
powershell
starts up powershell.exe, which is included in Windows 7-Command "... "
is a command line arg for powershell.exe containing the command to run(gc myFile.txt)
reads the content ofmyFile.txt
(gc
is short for theGet-Content
command)-replace 'foo', 'bar'
simply runs the replace command to replacefoo
withbar
| Out-File myFile.txt
pipes the output to the filemyFile.txt
-encoding ASCII
prevents transcribing the output file to unicode, as the comments point out
Powershell.exe should be part of your PATH statement already, but if not you can add it. The location of it on my machine is C:\WINDOWS\system32\WindowsPowerShell\v1.0
Update
Apparently modern windows systems have PowerShell built in allowing you to access this directly using
(Get-Content myFile.txt) -replace 'foo', 'bar' | Out-File -encoding ASCII myFile.txt
File get contents and string replace for multiple files
Just foreach
what you want:
foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
$file = file_get_contents("./test/$filename");
if(strpos($file, "Hello You") !== false){
echo "Already Replaced";
}
else {
$str = str_replace("Go Away", "Hello You", $file);
file_put_contents("./test/$filename", $str);
echo "done";
}
}
You don't need the if
unless you really need the echo
s to see when there are replacements:
foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
$file = file_get_contents("./test/$filename");
$str = str_replace("Go Away", "Hello You", $file);
file_put_contents("./test/$filename", $str);
}
Or you can get the count of replacements:
$str = str_replace("Go Away", "Hello You", $file, $count);
if($count) {
file_put_contents("./test/$filename", $str);
}
On Linux you could also try exec
or something with replace or repl as they accept multiple files.
Related Topics
How to Interact with the Recaptcha Audio Element Using Selenium and Python
How to Remove Specific Tag/Sticker/Object from Images Using Opencv
Tkinter Grid_Forget Is Clearing the Frame
How to Efficiently Handle European Decimal Separators Using the Pandas Read_CSV Function
How Does Python's "Super" Do the Right Thing
How to Normalize JSON Correctly by Python Pandas
When to Use Sys.Path.Append and When Modifying %Pythonpath% Is Enough
How to Read One Single Line of CSV Data in Python
Get First Row Value of a Given Column
Django Template System, Calling a Function Inside a Model
How to Do Row-To-Column Transposition of Data in CSV Table
Replace Invalid Values with None in Pandas Dataframe
Python - Read File from and to Specific Lines of Text
Why Do I Need to Deploy a "Default" App Before I Can Deploy Multiple Services in Gae
How to Enumerate a Range of Numbers Starting at 1
Why Is Pip Installing an Old Version of My Package