使用批处理文件在文本文件中添加新行,而不更改格式

时间:2011-09-13 08:00:41

标签: batch-file

这是我的剧本。

@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

1 个答案:

答案 0 :(得分:4)

使用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%