How to Search and Replace Text in a File

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='')

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

How to find and replace text in a file

Read all file content. Make a replacement with String.Replace. Write content back to file.

string text = File.ReadAllText("test.txt");
text = text.Replace("some text", "new value");
File.WriteAllText("test.txt", text);

Several find and replace from text file

Using the regex supplied by jay.sf, you could use str_replace_all from the stringr package to do it with a named vector.

library(stringr)

new_tx <- str_replace_all(tx,
c("\\sis taken on\\s" = " ",
"\\b\\sat\\s" = "\t",
"\\b\\sp\\b" = ","))

cat(new_tx)

Result

-The data 1 Aug, 2009    UBC
and is significant with, value <0.01

-The data 2 Sep, 2012 SFU
and is not significant with, value > 0.06

replacing text in a file with Python

This should do it

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
outfile.write(line)

EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:

lines = []
with open('path/to/input/file') as infile:
for line in infile:
for src, target in replacements.items():
line = line.replace(src, target)
lines.append(line)
with open('path/to/input/file', 'w') as outfile:
for line in lines:
outfile.write(line)

Edit: If you are using Python 2.x, use replacements.iteritems() instead of replacements.items()

how to Find and replace text with in a file from terminal using vim editor

You could use sed:

sed -ie "s/>/\">\"/g" /path/to/file
  • -i: edit in place
  • -e: run the following command
  • "s/text/replacement/g": replace every occurrence of text with replacement

Replace text in a file between two strings from another text file using python

Read the contents of your file into a string.

with open('your_file', 'r') as f:
contents = f.read()

Get the text between the two occurrences.

starting_text = 'whatever your first bound is'
ending_text = 'whatever your second bound is'
to_replace = contents[contents.find(starting_text)+len(starting_text):contents.rfind(ending_text)]

Then replace it.

contents = contents.replace(to_replace, 'whatever you want to replace it with')

And then you can rewrite it back into a file.

You could use the same approach to find the text that you're going to replace it with if it's in another file.

(This isn't compiled by the way, so it may not be entirely correct)

Find and replace within a text file using Python

How about this:

sed -i 's/;/ /g' yourBigFile.txt

This is not a Python solution. You have to start this in a shell. But if you use Notepad, I guess you are on Windows. So here a Python solution:

f1 = open('yourBigFile.txt', 'r')
f2 = open('yourBigFile.txt.tmp', 'w')
for line in f1:
f2.write(line.replace(';', ' '))
f1.close()
f2.close()

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)



Related Topics



Leave a reply



Submit