Find and Replace in a File

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

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)

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 text in a 47GB large file

Sed (stream editor for filtering and transforming text) is your friend.

sed -i 's/old text/new text/g' file

Sed performs text transformations in a single pass.

How do I find and replace all occurrences (in all files) in Visual Studio Code?

Since version 1.3 of vscode this is possible

  1. Navigate to the search, click icon to the left or:
    • (mac) cmd + shift + h
    • (PC) ctrl + shift + h
  2. expand replace
  3. enter search term and replace term
  4. confirm!

Search and replace with vscode

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

linux command to find files and replace with another file

Assuming you have the replacement file in your home directory (~), you can use find to do the replacing. This will find all boom.txt files and replace them with the replace.txt file (keeping the boom.txt name).

find . -name "boom.txt" -exec cp ~/replace.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);

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html



Related Topics



Leave a reply



Submit