1

This is my script.

@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

This script I save as run1.bat. After running, I have problem with the format. The format is out of order: trailing tab characters are removed. How to fix it?

Original file:

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

Output:

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
newbie18
  • 323
  • 1
  • 3
  • 6
  • I took the liberty of rephrasing your question a little, to clarify it. Please review it and, if I've got it wrong, feel free to edit it again to whatever form you think right. – Andriy M Sep 13 '11 at 09:29

1 Answers1

4

Reading with set /p is really powerfull, as it doesn't change any character.
But it removes (extra) trailing CR/LF/TAB characters.

How set/p works is explained here How Set/p works and here New technic: set /p can read multiple lines from a file

For solving your problem and preserve the trailing tabs, you need the delayed toggling technic.

So your code would look like this

@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%
Community
  • 1
  • 1
jeb
  • 78,592
  • 17
  • 171
  • 225