从Windows批处理文件替换文本文件中的字符 [英] Replacing characters in a text file from Windows batch file
问题描述
我正在尝试编写一个批处理文件,该文件将查看一个小文本文件(实际上是CUE表)中的每个字符,并执行三件事-删除所有问号,用连字符替换任何斜杠,然后替换带有两个连字符的冒号-按照下面示例中的第二行.
I'm trying to write a batch file that will look at every character in a small text file (a CUE sheet, actually) and do three things -- remove all question marks, replace any slash marks with a hyphen and replace colons with two hyphens -- as per the second line in the example below.
TRACK 01 AUDIO
TITLE "Colon: Slash / Question Mark?"
(would be changed to)
TITLE "Colon -- Slash - Question Mark"
我知道如何使用findstr将包含那些字符的行复制到新的文本文件(但仅限那些行)中,而不是如何进行搜索和替换. findstr还具有删除前导空格的不良后果,我希望保留该空格.不知道这里正确的方法是什么. (我应该补充一点,由于种种原因,我宁愿不使用第三方实用程序.)
I know how to use findstr to copy the lines containing those characters to a new text file (but only those lines), and not how to do the search-and-replace. And findstr also has the unwanted consequence of removing leading spaces, which I wish to retain. Not sure what's the right approach here. (I should add that for various reasons I prefer not to use a third-party utility.)
推荐答案
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q42482508.txt"
SET "outfile=%destdir%\outfile.txt"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
SET "line=%%a"
SET "line=!line:?=!"
SET "line=!line:/=-!"
SET "line=!line::=--!"
ECHO !line!
)
)>"%outfile%"
GOTO :EOF
您需要根据自己的情况更改sourcedir
和destdir
的设置.
You would need to change the settings of sourcedir
and destdir
to suit your circumstances.
我使用了一个名为q42482508.txt
的文件,其中包含您的数据用于测试.
I used a file named q42482508.txt
containing your data for my testing.
产生定义为%outfile%
Produces the file defined as %outfile%
调用延迟扩展以允许在代码块中操作字符串.
Invoke delayed expansion to allow strings to be manipulated in a code block.
从line
开始将文件的每一行读取到%%a
;将每个?
都替换为 ,将/
替换为一个-
,将:
替换为两个,然后将echo
替换为结果.
Read each line of the file to %%a
thence line
; replace each ?
with nothing, /
with one -
and :
with two, and echo
the result.
将for
括住括号可以重定向到指定的文件.
Parenthesising the for
allows redirection to the specified file.
模式设置为"var1 =!var2:字符串替换 = 替换字符串!"如记录所示,使用!
代替%
可以使用延迟扩展.
The pattern is set "var1=!var2:stringtoreplace=replacementstring!" as documented, !
in place of %
to use delayedexpansion.
请注意,您的文本将:
的替换字符串指定为--
,而您的示例显示了它被替换为"空格-"
Note that your text specifies the replacemnt string for :
as --
whereas your example shows it being replaced by "Space--"
这篇关于从Windows批处理文件替换文本文件中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!