如何替换文本文件中的字母?

如何替换文本文件中的字母?

我有一个名为的文本文件,file.txt它包含,

i love bats and batch

我喜欢bc

预期输出在单独的文件中output.txt

i love cats and catch

重要的提示 :它只能替换字母,而不是替换整个单词。

我正在使用代码,

set /p "input=<file.txt"
set b=c >>output.txt

但是,我接受批处理时出现空白output.txt。如何修复我的代码?

答案1

该行将set b=c值分配c给变量b,这不是您所需要的。

如果输入文件仅包含一行,则以下代码可以执行您想要的操作:

rem // Read (first) line from input file into variable:
set /P input=<"file.txt"
rem // Replace `b` with `c` and write result to output file:
echo/%input:b=c%>>"output.txt"

答案2

假设一行包含不超过 8 个字母b

setlocal enabledelayedexpansion
for /f "delims=b tokens=1,2,3,4,5,6,7,8,9" %%a in (file.txt) do (
    set new=%%a
    if not ""=="%%b" set new=!new!c%%b
    if not ""=="%%c" set new=!new!c%%c
    if not ""=="%%d" set new=!new!c%%d
    if not ""=="%%e" set new=!new!c%%e
    if not ""=="%%f" set new=!new!c%%f
    if not ""=="%%g" set new=!new!c%%g
    if not ""=="%%h" set new=!new!c%%h
    if not ""=="%%i" set new=!new!c%%i
    echo !new!>>output.txt
)

如果有超过 8 个b符号,则第 9 个符号之后的其余部分将会丢失。

答案3

@aschipfl 的方法可以适用于替换整个文件中的字符串,如下所示:

@ECHO OFF
SETLOCAL enableDelayedExpansion
set /P "input=Drop your file here: >"
Set /p Replace=[String to replace:]
Set /p With=[Replacement text:]
FOR /F "Tokens=* Delims=" %%l IN (%input%) DO (
rem // Read (lines by token) from input file into variable:
set output=%%l
rem // Replace `b` with `c` and write result to output file:
CALL :write
)

START notepad.exe "output.txt"
pause

REM I had to cheat and use a variable to Get the Output substituion to Expand properly.

:write
set "Substitute=!output:%Replace%=%With%!"
echo/%Substitute%>>"output.txt"
GOTO :EOF

*注释*

- The filename input method is not Suitbale file pathways with Spaces.
- There are limits to the number of tokens, and therefor the number of lines this method will work for is limited.
- Lack of input validation means it's only suitable for plain text, Not code.

相关内容