如何使用Windows命令行環境查找和替換文件中的文本?


Answers

這裡的很多答案幫助我指出了正確的方向,但是沒有一個適合我,所以我發布了我的解決方案。

我有Windows 7,它內置了PowerShell。 以下是我用來查找/替換文件中所有文本實例的腳本:

powershell -Command "(gc myFile.txt) -replace 'foo', 'bar' | Out-File myFile.txt"

解釋它:

  • powershell啟動powershell.exe,它包含在Windows 7中
  • -Command "... "是包含要運行的命令的powershell.exe的命令行參數
  • (gc myFile.txt)讀取(gc myFile.txt)的內容( gcGet-Content命令的縮寫)
  • 替換-replace 'foo', 'bar'只需運行replace命令來替換foo
  • | Out-File myFile.txt | Out-File myFile.txt將輸出傳遞到文件myFile.txt

Powershell.exe應該已經成為您的PATH語句的一部分,但是如果沒有,您可以添加它。 它在我的機器上的位置是C:\WINDOWS\system32\WindowsPowerShell\v1.0

Question

我正在使用Windows命令行環境編寫批處理文件腳本,並且希望將文件中某些文本(例如“FOO”)的每個出現與另一個(例如“BAR”)進行更改。 什麼是最簡單的方法來做到這一點? 任何內置函數?




I have used perl, and that works marvelously.

perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" <fileName>

.orig is the extension it would append to the original file

For a number of files matching such as *.html

for %x in (<filePattern>) do perl -pi.orig -e "s/<textToReplace>/<textToReplaceWith>/g;" %x



Two batch files that supply search and replace functions have been written by members dbenham and aacini using native built-in jscript in Windows.

They are both robust and very swift with large files compared to plain batch scripting, and also simpler to use for basic replacing of text. They both have Windows regular expression pattern matching.

======================================================================================

1) This sed-like helper batch file is called repl.bat (by dbenham) - download from: https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

Example using the L literal switch:

echo This is FOO here|repl "FOO" "BAR" L
echo and with a file:
type "file.txt" |repl "FOO" "BAR" L >"newfile.txt"

======================================================================================

2) This grep-like helper batch file is called findrepl.bat (by aacini) - download from: https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

Example which has regular expressions active:

echo This is FOO here|findrepl "FOO" "BAR" 
echo and with a file:
type "file.txt" |findrepl "FOO" "BAR" >"newfile.txt"

======================================================================================

Both become powerful system-wide utilities when placed in a folder that is on the path , or can be used in the same folder with a batch file, or from the cmd prompt.

They both have case-insensitive switches and also many other functions.




@Rachel gave an excellent answer but here is a variation of it to read content to a powershell $data variable. You may then easily manipulate content multiple times before writing to a output file. Also see how multi-line values are given in a .bat batch files.

@REM ASCII=7bit ascii(no bom), UTF8=with bom marker
set cmd=^
  $old = '\$Param1\$'; ^
  $new = 'Value1'; ^
  [string[]]$data = Get-Content 'datafile.txt'; ^
  $data = $data -replace $old, $new; ^
  out-file -InputObject $data -encoding UTF8 -filepath 'datafile.txt';
powershell -NoLogo -Noninteractive -InputFormat none -Command "%cmd%"



Just faced a similar problem - "Search and replace text within files", but with the exception that for both filenames and search/repalce I need to use regex. Because I'm not familiar with Powershell and want to save my searches for later use I need something more "user friendly" (preferable if it has GUI).

So, while Googling :) I found a great tool - FAR (Find And Replace) (not FART).

That little program has nice GUI and support regex for searching in filenames and within files. Only disadventage is that if you want to save your settings you have to run the program as an administrator (at least on Win7).




Use powershell in .bat - for Windows 7+

encoding utf8 is optional, good for web sites

@echo off
set ffile='myfile.txt'
set fold='FOO'
set fnew='BAR'
powershell -Command "(gc %ffile%) -replace %fold%, %fnew% | Out-File %ffile% -encoding utf8"



I have faced this problem several times while coding under Visual C++. If you have it, you can use Visual studio Find and Replace Utility. It allows you to select a folder and replace the contents of any file in that folder with any other text you want.

Under Visual Studio: Edit -> Find and Replace In the opened dialog, select your folder and fill in "Find What" and "Replace With" boxes. Hope this will be helpful.




使用FNR

使用fnr工具。 與fart相比,它有一些優勢:

  • 常用表達
  • 可選的GUI。 有一個“生成命令行按鈕”來創建命令行文本來放入批處理文件。
  • 多線模式:使用GUI可以輕鬆處理多線模式。 在FART中,您不得不手動換行換行符。
  • 允許您選擇文本文件編碼。 還有一個自動檢測選項。

在這裡下載FNR: http://findandreplace.codeplex.com/ : http://findandreplace.codeplex.com/

用法示例: fnr --cl --dir "<Directory Path>" --fileMask "hibernate.*" --useRegEx --find "find_str_expression" --replace "replace_string"




Take a look at Is there any sed like utility for cmd.exe which asked for a sed equivalent under Windows, should apply to this question as well. 執行摘要:

  • It can be done in batch file, but it's not pretty
  • Lots of available third party executables that will do it for you, if you have the luxury of installing or just copying over an exe
  • Can be done with VBScript or similar if you need something able to run on a Windows box without modification etc.



Here's a solution that I found worked on Win XP. In my running batch file, I included the following:

set value=new_value

:: Setup initial configuration
:: I use && as the delimiter in the file because it should not exist, thereby giving me the whole line
::
echo --> Setting configuration and properties.
for /f "tokens=* delims=&&" %%a in (config\config.txt) do ( 
  call replace.bat "%%a" _KEY_ %value% config\temp.txt 
)
del config\config.txt
rename config\temp.txt config.txt

The replace.bat file is as below. I did not find a way to include that function within the same batch file, because the %%a variable always seems to give the last value in the for loop.

replace.bat :

@echo off

:: This ensures the parameters are resolved prior to the internal variable
::
SetLocal EnableDelayedExpansion

:: Replaces Key Variables
::
:: Parameters:
:: %1  = Line to search for replacement
:: %2  = Key to replace
:: %3  = Value to replace key with
:: %4  = File in which to write the replacement
::

:: Read in line without the surrounding double quotes (use ~)
::
set line=%~1

:: Write line to specified file, replacing key (%2) with value (%3)
::
echo !line:%2=%3! >> %4

:: Restore delayed expansion
::
EndLocal



我知道我遲到了..

就我個人而言,我喜歡這個解決方案: - http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace

我們還廣泛使用重複數據刪除功能,幫助我們每天通過SMTP發送大約500封電子郵件: https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o ://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o

而且這些都可以在本地工作而無需額外的工具或實用程序。

替代品:

DEL New.txt
setLocal EnableDelayedExpansion
For /f "tokens=* delims= " %%a in (OLD.txt) do (
Set str=%%a
set str=!str:FOO=BAR!
echo !str!>>New.txt
)
ENDLOCAL

DEDUPLICATOR(注意使用-9作為ABA編號):

REM DE-DUPLICATE THE Mapping.txt FILE
REM THE DE-DUPLICATED FILE IS STORED AS new.txt

set MapFile=Mapping.txt
set ReplaceFile=New.txt

del %ReplaceFile%
::DelDupeText.bat
rem https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/sj8IUhMOq6o
setLocal EnableDelayedExpansion
for /f "tokens=1,2 delims=," %%a in (%MapFile%) do (
set str=%%a
rem Ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.RightString
set str=!str:~-9!
set str2=%%a
set str3=%%a,%%b

find /i ^"!str!^" %MapFile%
find /i ^"!str!^" %ReplaceFile%
if errorlevel 1 echo !str3!>>%ReplaceFile%
)
ENDLOCAL

謝謝!




替換 - 使用字符串替換替換子字符串描述:要用另一個字符串替換子字符串,請使用字符串替換功能。 這裡顯示的例子用字符串變量str中的“the”替換所有出現的“teh”拼寫錯誤。

set str=teh cat in teh hat
echo.%str%
set str=%str:teh=the%
echo.%str%

腳本輸出:

teh cat in teh hat
the cat in the hat

ref: http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace : http://www.dostips.com/DtTipsStringManipulation.php#Snippets.Replace







Related