标题: [文本处理] 批处理输入字符进行指定字符串替换遇到的问题~ [打印本页]
作者: psstudio 时间: 2023-12-18 12:26 标题: 批处理输入字符进行指定字符串替换遇到的问题~
- @echo off
- setlocal enabledelayedexpansion
-
- set/p a=请输入数值,多个可加空格:
-
- for %%i in (!a!) do (
-
- set "inputFile=1.txt"
- set "searchString=10000"
- set /a sum=!searchString!+%%i
- set "replaceString=!sum!"
-
- for /f "tokens=*" %%b in (!inputFile!) do (
- set "line=%%b"
- call set "newLine=%%line:!searchString!=!replaceString!%%"
- echo !newLine! >> temp.txt
- )
- )
-
- pause
复制代码
代码能正常跑,但是生成的temp.txt内容里和原来的1.txt内容有出入,原文本里的空格没有了! 而且每一行前面的空格也没有了!请教一下大神这种该如何修改?
1.txt的内容如下:
-----------------------------
srv_domain: xxx.com
port: 10000
main:
password: password
bg:
pa1: ./1.pa1
pa2: ./2.pa2
-----------------------------
作者: Batcher 时间: 2023-12-18 14:57
回复 1# psstudio
请参考Q-13:把等号左右两边的空格都删掉
https://mp.weixin.qq.com/s/Koje4FufWxWBs7ioDy_LJA
作者: psstudio 时间: 2023-12-18 15:31
自己解决了~网上找了一段代码:
for /f "tokens=1* delims=:" %%i in ('findstr /n .* "!inputFile!"') do (
set "lineContent=%%j"
if not "!lineContent!"=="" call set "lineContent=%%lineContent:!searchString!=!replaceString!%%"
>>"temp.txt" echo.!lineContent!
)
作者: Batcher 时间: 2023-12-18 15:39
回复 3# psstudio - @echo off
- setlocal enabledelayedexpansion
- set /p a=请输入数值,多个可加空格:
- set "inputFile=1.txt"
- set "searchString=10000"
- (for %%i in (!a!) do (
- set /a sum=!searchString!+%%i
- set "replaceString=!sum!"
- for /f "tokens=1* delims=:" %%a in ('findstr /n .* "!inputFile!"') do (
- if "%%b" == "" (
- echo,
- ) else (
- set "line=%%b"
- call set "newLine=%%line:!searchString!=!replaceString!%%"
- echo !newLine!
- )
- )
- ))>"temp.txt"
- pause
复制代码
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |