command-line script教學 - 如何使用Windows命令行環境查找和替換文件中的文本?





create print (23)


@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%"

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




如果您使用支持.Net 2.0的Windows版本,則會替換您的外殼。 PowerShell從命令行為您提供.Net的全部功能。 還有許多內置的命令行。 下面的例子將解決你的問題。 我使用的是命令的完整名稱,有一些更短的別名,但是這給了你一些Google的幫助。

(Get-Content test.txt) | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt



Can also see the Replace and ReplaceFilter tools at https://zoomicon.github.io/tranXform/ (source included). The 2nd one is a filter.

The tool that replaces strings in files is in VBScript (needs Windows Script Host [WSH] to run in old Windows versions)

The filter is probably not working with Unicode unless you recompile with latest Delphi (or with FreePascal/Lazarus)




替換 - 使用字符串替換替換子字符串描述:要用另一個字符串替換子字符串,請使用字符串替換功能。 這裡顯示的例子用字符串變量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




創建文件replace.vbs:

Const ForReading = 1    
Const ForWriting = 2

strFileName = Wscript.Arguments(0)
strOldText = Wscript.Arguments(1)
strNewText = Wscript.Arguments(2)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)
strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, strOldText, strNewText)
Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewText  'WriteLine adds extra CR/LF
objFile.Close

要使用此修訂後的腳本(我們將其稱為replace.vbs),只需在命令提示符下鍵入與此類似的命令即可:

cscript replace.vbs "C:\Scripts\Text.txt" "Jim " "James "




我知道我遲到了..

就我個人而言,我喜歡這個解決方案: - 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

謝謝!




Download Cygwin (free) and use unix-like commands at the Windows command line.

Your best bet: sed




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).




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

我有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




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"



我不認為有任何內置命令可以做到這一點。 我建議你下載Gnuwin32UnxUtils類的東西,並使用sed命令(或僅下載sed ):

sed -c s/FOO/BAR/g filename



使用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"




剛剛使用了FART (“ F ind AR eplace T ext”命令行工具):
在一大組文件中用於文本替換的優秀小免費軟件。

安裝文件位於SourceForge上

用法示例:

fart.exe -p -r -c -- C:\tools\perl-5.8.9\* @@[email protected]@ C:\tools

將預覽這個替代品在這個Perl發行版的文件中遞歸地執行。

唯一的問題:FART網站圖標不完美,精緻或優雅;)

2017年更新(7年後) jagb MikailTunço2011年發表的文章快速找到並替換文本 ”中指出:




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.




When you work with Git on Windows then simply fire up git-bash and use sed . Or, when using Windows 10, start "Bash on Ubuntu on Windows" (from the Linux subsystem) and use sed .

Its a stream editor, but can edit files directly by using the following command:

sed -i -e 's/foo/bar/g' filename
  • -i option is used to edit in place on filename.
  • -e option indicates a command to run.
    • s is used to replace the found expression "foo" with "bar" and g is used to replace any found matches.

Note by ereOn:

If you want to replace a string in versioned files only of a Git repository, you may want to use:

git ls-files <eventual subfolders & filters> | xargs sed -i -e 's/foo/bar/g'

which works wonders.







I played around with some of the existing answers here and prefer my improved solution...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }"

or if you want to save the output again to a file...

type test.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"foo\", \"bar\" }" > outputFile.txt

The benefit of this is that you can pipe in output from any program. Will look into using regular expressions with this too. Couldn't work out how to make it into a BAT file for easier use though... :-(




Power shell command works like a charm

(
test.txt | ForEach-Object { $_ -replace "foo", "bar" } | Set-Content test2.txt
)



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



With the replacer.bat

1) With e? option that will evaluate special character sequences like \n\r and unicode sequences. In this case will replace quoted "Foo" and "Bar" :

call replacer.bat "e?C:\content.txt" "\u0022Foo\u0022" "\u0022Bar\u0022"

2) Straightforward replacing where the Foo and Bar are not quoted.

call replacer.bat "C:\content.txt" "Foo" "Bar"



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.



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



如果您已經有數據庫使用以下內容導入dumpsql文件

mysql -u username -p database_name < file.sql

如果你不需要在MySQL中創建相關數據庫(空),那麼首先通過在終端或cmd中運行以下命令來登錄到MySQL控制台

mysql -u userName -p;

並在出現提示時提供密碼。

接下來創建一個數據庫並使用它

mysql>create database yourDatabaseName;
mysql>use yourDatabaseName;

然後將sqldump文件從數據庫導入到數據庫中

mysql> source pathToYourSQLFile;

注意:如果您的終端不在dumpsql文件所在的位置,請使用上面的相對路徑。





windows command-line scripting batch-file text-files