我正在编写一个.bat程序,它将查找并替换文件中的文本。我遇到的问题是它正在移除空白行并左对齐其他行。我需要保留空行并将新文本保留在同一位置。这是我写的,也是结果。任何人都可以帮忙。
程序:
@ECHO OFF
cls
cd\
c:
setLocal EnableDelayedExpansion
For /f "tokens=* delims= " %%a in (samplefile.tx) do (
Set str=%%a
set str=!str:day=night!
set str=!str:winter=summer!
echo !str!>>samplefile2.txt)
ENDLOCAL
cls
exit
samle文件:
this line is the first line in my file that I am using as an example.This is made up text
the cat in the hat
day
winter
下面是结果:
this line is the first line in my file that I am using as an example.This is made up text
the cat in the hat
night
summer
我需要在替换文本时保持行,空格和新文本保持在相同的位置。请帮忙
答案 0 :(得分:0)
@ECHO Off
SETLOCAL
(
FOR /f "tokens=1*delims=]" %%a IN ('find /n /v "" q27459813.txt') DO (
SET "line=%%b"
IF DEFINED line (CALL :subs) ELSE (ECHO()
)
)>newfile.txt
GOTO :EOF
:subs
SET "line=%line:day=night%"
SET "line=%line:winter=summer%"
ECHO(%line%
GOTO :eof
这应该适合你。我使用了一个名为q27459813.txt
的文件,其中包含我的测试数据。
制作newfile.txt
如果数据文件行以]
开始,则无法正常工作。
修改为允许引导]
@ECHO Off
SETLOCAL
(
FOR /f "delims=" %%a IN ('type q27459813.txt^|find /n /v "" ') DO (
SET "line=%%a"
CALL :subs
)
)>newfile.txt
GOTO :EOF
:subs
SET "line=%line:*]=%"
IF NOT DEFINED line ECHO(&GOTO :EOF
SET "line=%line:day=night%"
SET "line=%line:winter=summer%"
ECHO(%line%
GOTO :eof
答案 1 :(得分:0)
"tokens=* delims= "
会修剪前导空格。相反,请使用"delims="
来保留前导空格。FIND
或FINDSTR
用于在每行的前面插入行号。!var:*:=!
删除FINDSTR中的行号前缀。echo(!str!
来阻止ECHO is off
消息@echo off
setlocal enableDelayedExpansion
>samplefile2.txt (
for /f "delims=" %%A in ('findstr /n "^" samplefile.txt') do (
set "str=%%A"
set "str=!str:*:=!"
set "str=!str:day=night!"
set "str=!str:winter=summer!"
echo(!str!
)
)
这仍然存在潜在问题。由于扩展延迟,当!
展开时,它会损坏包含%%A
的行。诀窍是在循环内打开和关闭延迟扩展。
@echo off
setlocal disableDelayedExpansion
>samplefile2.txt (
for /f "delims=" %%A in ('findstr /n "^" samplefile.txt') do (
set "str=%%A"
setlocal enableDelayedExpansion
set "str=!str:*:=!"
set "str=!str:day=night!"
set "str=!str:winter=summer!"
echo(!str!
endlocal
)
)
或者您可以完全忘记自定义批处理,并使用我的JREPL.BAT utility that performs regular expression search and replace on text获得更简单,更快速的解决方案。可以选择指定多个文字搜索/替换对。
jrepl "day winter" "night summer" /t " " /l /i /f sampleFile.txt /o sampleFile2.txt
我使用/I
选项使搜索大小写不敏感。但是如果您愿意,可以放弃该选项以使其区分大小写。使用纯批次无法轻松完成。