.bat查找和替换文本

时间:2010-08-31 14:15:17

标签: batch-file windows-scripting

我有一些文件包含以下所有内容:

程序RxBIN RXPCN RxGroup MemberID

并非所有文件都包含所有这些标题,但我需要替换它们,所以它看起来像这样:

@Program @RxBIN @RXPCN @RxGroup @MemberID

先谢谢, 乔

2 个答案:

答案 0 :(得分:2)

我仍然倾向于使用为此目的而构建的工具:Batch Replacer似乎完全符合该法案。

但是,如果你已经死了......使用带有多个arg解析器的旧repl.bat ......这会变成一个使用DEBUG命令的怪物,但这里是最后的杰作:

源代码: mmrepl.bat

@ECHO OFF
setLocal EnableDelayedExpansion

::: mmrepl - Replaces one or more strings with others, in file(s)
:::
::: syntax: mmrepl.bat $file $find $replace [$find $replace] ...
:::            $file    [in] - file to be parsed
:::            $find    [in] - string to find
:::            $replace [in] - string to replace with
:::
:::         * $find & $replace should be supplied in pairs, n multiples allowed
:::         * $file can be a single file (eg.txt) or a file filter (*.txt)
:::           you can supply any command that works with 'dir /b $file'
:::           so paths and drives are also valid.
:::         * $find,$replace strings can be single words, or strings enclosed
:::            in quotes (which will be stripped)
if "%~1"=="" findstr "^:::" "%~f0"&GOTO:EOF
if not exist %1 echo No files matching %1 found&GOTO:EOF

::Creates the following log file:
set log=%0.log
::Temporarily creates the following files but cleans up
set replscr=TEMPDEBUG.SCR
set cmplsrc=TEMPEDLN.SCR

echo To see the work of %0.bat view the log file %log%
echo Multi-Multi Replacement (%0.bat)>%log%
echo.>>%log%
set "files=%1"
shift
set mmreplcmd=
:: Pair up find/replaces
:strippairs
set p1=%1
set p1=!p1:"=!
set p2=%2
set p2=!p2:"=!
SET mmreplcmd=%mmreplcmd%'1R%p1%' 1A '%p2%' 0D 0A 
echo Replacing "%p1%" with "%p2%" >> %log%
shift
shift
if "%~1" neq "" goto:strippairs

::Build script
echo N%cmplsrc% > %replscr%
echo E CS:100 %mmreplcmd%'E' 0D 0A>> %replscr%
echo RCX >> %replscr%
echo 40 >> %replscr%
echo W >> %replscr%
echo Q >> %replscr%
DEBUG < %replscr% > NUL
::Execute on files
for /f %%a IN ('dir /b %files%') do (
  echo.>>%log%
  echo *** File: %%a >> %log%
  EDLIN %%a < %cmplsrc% >> %log%
)
DEL %replscr%
DEL %cmplsrc%

注意:我必须在搜索 repl.bat 时删除“包含”,因为您要为每个标题添加一个&符号,因此它始终包含..我的测试显示这个工作正常,但是YMMV(测试)。

答案 1 :(得分:1)

这可以通过sed several {{3}中适用于Windows的{{1>}( s tream ed itor)轻松完成}。

可以用

之类的东西来完成
sed -e "s/\(Program\|RxBIN\|RXPCN\|RxGroup\|MemberID\)/@\1/g" myfile.txt > newfile.txt

这是一个正则表达式,基本上表示“替换'Program'或'RxBIN'或'RXPCN'或'RxGroup'或'MemberID'这个词,一个符号和匹配的任何单词。”

有很多很棒的Unix命令已经移植到Windows,这些命令非常有用。