Replace String Within File Contents

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 of myFile.txt (gc is short for the Get-Content command)
  • -replace 'foo', 'bar' simply runs the replace command to replace foo with bar
  • | Out-File myFile.txt pipes the output to the file myFile.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 echos 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



Leave a reply



Submit