这是我的脚本。
@ECHO OFF
SET origfile="C:\Documents and Settings\user\Desktop\test1\before.txt"
SET tempfile="C:\Documents and Settings\user\Desktop\test1\after.txt"
SET insertbefore=4
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
pause这个脚本我另存为run1.bat。运行后,我对格式有问题。格式无序:尾随的制表符被删除。如何修复它?
原始文件:
header 1<--here got tab delimited format--><--here got tab delimited format-->
header 2<--here got tab delimited format--><--here got tab delimited format-->
header 3<--here got tab delimited format--><--here got tab delimited format-->
details 1
details 2输出:
header 1<--tab delimited is missing--><--tab delimited is missing-->
header 2<--tab delimited is missing--><--tab delimited is missing-->
header 3<--tab delimited is missing--><--tab delimited is missing-->
details 1
details 2
details 3发布于 2011-09-13 21:29:14
用set /p阅读真的很强大,因为它不会改变任何字符。
但它会删除(额外的)尾随的CR/LF/TAB字符。
在这里How Set/p works和这里New technic: set /p can read multiple lines from a file解释了set/p的工作原理
为了解决您的问题并保留尾随选项卡,您需要delayed toggling technic。
因此,您的代码将如下所示
@echo off
SET origfile="C:\Documents and Settings\user\Desktop\test1\before.txt"
SET tempfile="C:\Documents and Settings\user\Desktop\test1\after.txt"
SET insertbefore=4
set LineCnt=0
SETLOCAL DisableDelayedExpansion
(
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ %origfile%"`) do (
set "var=%%a"
set /a lineCnt+=1
SETLOCAL EnableDelayedExpansion
set "var=!var:*:=!"
IF !lineCnt!==%insertbefore% ECHO(
echo(!var!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%https://stackoverflow.com/questions/7398594
复制相似问题