我需要运行批处理文件,这有助于我们的员工毫无困难地更改文本文件。
正如您所看到的,此文件中有很多空格,它们需要存在,否则无法在其他程序中导入。
我的问题:是否可以搜索特定列并将此值替换为用户输入?
我试图在谷歌的帮助下完成某项工作,这就是结果:
@echo off
for /f "skip=5 delims=" %%a in (Muster.dat) do set "var=%%a"&goto :done
:done
set "R_sph=%var:~126,5%"
echo R_sph: %R_sph%
set /p R_sph_new=Enter new sph:
echo R_sph neu: %R_sph_new%
set "search=R_sph"
set "replace=R_sph_new"
set "textfile=Muster.dat"
set "newfile=Muster2.dat"
(for /f "delims=" %%i in (%textfile%) do (
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!line:%search%=%replace%!"
echo(!line!
endlocal
))>"%newfile%"
del %textfile%
rename %newfile% %textfile%
pause
PS:我的批处理经验更糟,解释你发给我的代码中的每一步都会很棒。
编辑:我们每天都会生成大量这样的文件,其中只有一些需要编辑。这些文件的构造始终是相同的,但与其他值相同,所以它非常重要,因此请通过列进行搜索。
答案 0 :(得分:0)
set "search=R_sph"
set "replace=R_sph_new"
应
set "search=%R_sph%"
set "replace=%R_sph_new%"
即,将search
和replace
的值设置为变量的内容。您的代码会将search
设置为字符串 R_sph
。
?您确定R_sph
中的值在您的文件中是唯一的吗?
答案 1 :(得分:0)
更改批处理文件中的主循环,以便:
只是为了使批处理脚本更加健壮,您还可以验证用户输入,以确保他们输入的正好是5个字符作为替换字符串。
以下是包含建议更改的整个文件:
@echo off
setlocal enabledelayedexpansion
for /f "skip=5 delims=" %%a in (Muster.dat) do set "var=%%a"&goto :done
:done
set "R_sph=%var:~126,5%"
echo R_sph: %R_sph%
set /p R_sph_new=Enter new sph:
echo R_sph neu: %R_sph_new%
rem Validate user input - ensure it's exactly 5 characters
set "replace=%R_sph_new% "
set "replace=%replace:~0,5%"
if not "%R_sph_new%" == "%replace%" (
echo Don't be silly.
exit /b 1
)
set "textfile=Muster.dat"
set "newfile=Muster2.dat"
set /a lineNumber = 0
(for /f "delims=" %%i in (%textfile%) do (
set /a lineNumber += 1
set "line=%%i"
if !lineNumber! == 6 set "line=!line:~0,126!%replace%!line:~131!"
echo(!line!
))>"%newfile%"
rem It might be safer to rename %textfile% to %textfile%.BAK instead of deleting it.
del %textfile%
rename %newfile% %textfile%
endlocal
pause
答案 2 :(得分:0)
非常感谢Klitos Kyriacou,这正是我想要的! 但不幸的是,这个批处理不会改变这个文本文件中的任何内容,整个代码如下所示:
@echo off
:R_sph
for /f "skip=5 delims=" %%a in (Muster.dat) do set "var=%%a"&goto :done
:done
set "R_sph=%var:~49,5%"
echo R_sph: %R_sph%
set /p R_sph_new=Enter new sph:
set "replace=%R_sph_new%"
set "textfile=Muster.dat"
set "newfile=Muster2.dat"
setlocal enabledelayedexpansion
set /a lineNumber = 0
(for /f "delims=" %%i in (%textfile%) do (
set /a lineNumber += 1
set "line=%%i"
if !lineNumber! == 6 set "line=!line:~0,49!%replace%!line:~54!"
echo(!line!
))>"%newfile%"
endlocal
:replace file
del %textfile%
rename %newfile% %textfile%
pause
编辑:我很着急,不知道如何设置它。现在我改变了代码并且它正在工作!