使用.cmd文件在txt文件中查找和替换

时间:2012-11-21 19:04:53

标签: batch-file cmd

我创建了一个.cmd文件,该文件将文件名作为参数,然后它要求查找字符串然后再替换字符串。

期望输出

发现这应该从替换为给定的文件替换,但它不起作用

以下是我试过的代码..

@echo off
setlocal enabledelayedexpansion

if not exist "%1" (echo this file does not exist...)&goto :eof

set /p findthis=find this text string:
set /p replacewith=and replace it with this:


for /f "tokens=*" %%a in (%1) do (

   set write=%%a
   if %%a==%findthis% set write=%replacewith%

   echo !write! 
   echo !write! >>%~n1.replaced%~x1
)

谢谢

1 个答案:

答案 0 :(得分:0)

我修复了你的代码中的一些简单错误。您应该将字符串放在引号中,因为它们很可能包含空格。有时它们可​​能是一个空字符串,导致回声问题,所以我添加了一个“;”回应处理:

@echo off
setlocal enabledelayedexpansion

if not exist "%1" (echo this file does not exist...)&goto :eof

set /p findthis=find this text string:
set /p replacewith=and replace it with this:


for /f "tokens=*" %%a in (%1) do (

   set write=%%a
   if "%%a"=="%findthis%" set write=%replacewith%

   echo;!write! 
   echo;!write! >>%~n1.replaced%~x1
)

但是,这只能匹配并替换整行,而不是一行中的文本字符串。要替换行中的子字符串,您必须使用变量字符串替换语法(在问题中多次引用:here和最后here

后一个答案包含解决原始问题所需的一切。

相关问题