1

我有一些文件包含以下部分(如果不是全部):

程序 RxBIN RXPCN RxGroup MemberID

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

@Program @RxBIN @RXPCN @RxGroup @MemberID

在此先感谢,乔

4

2 回答 2

2

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

但是,如果你死心塌地……使用带有多参数解析器的旧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(测试)。

于 2010-09-02T19:18:10.353 回答
1

这可以通过在多个地方适用于 Windows 的sed流式编辑器)轻松完成。

它可以用类似的东西来完成

sed -e "s/\(Program\|RxBIN\|RXPCN\|RxGroup\|MemberID\)/@\1/g" myfile.txt > newfile.txt

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

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

于 2010-09-02T19:42:21.070 回答