script - 如何使用Windows命令行环境查找和替换文件中的文本?




windows bat教程 (18)

我正在使用Windows命令行环境编写批处理文件脚本,并且希望将文件中某些文本(例如“FOO”)的每个出现与另一个(例如“BAR”)进行更改。 什么是最简单的方法来做到这一点? 任何内置函数?

https://code.i-harness.com


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



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

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)


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

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.


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... :-(


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


Power shell command works like a charm

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

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.

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.


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"

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"

刚刚使用了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 jagb的2011年文章“ 快捷方式 - 查找和替换文本 ”的评论中指出


如果您使用支持.Net 2.0的Windows版本,则会替换您的外壳。 PowerShell从命令行为您提供.Net的全部功能。 还有许多内置的命令行。 下面的例子将解决你的问题。 我使用的是命令的完整名称,有一些更短的别名,但是这给了你一些Google的帮助。

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

我不认为有任何内置命令可以做到这一点。 我建议你下载Gnuwin32UnxUtils类的东西,并使用sed命令(或仅下载sed ):

sed -c s/FOO/BAR/g filename

替换 - 使用字符串替换替换子字符串描述:要用另一个字符串替换子字符串,请使用字符串替换功能。 这里显示的例子用字符串变量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


这里的很多答案帮助我指出了正确的方向,但是没有一个适合我,因此我发布了我的解决方案。

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







text-files