Mahmoud Mostafa
Mahmoud Mostafa

Reputation: 17

Batch file to rewrite txt file starting from last line

lets say that i have test.txt with this lines

1
2
3

i need batch file to rewrite this file as

3
2
1

in new txt file

i tried this to copy last line

for /f "delims=" %%A in (ttt.txt) do set last=%%A
echo %last%>>ttt_lastline.txt

and this to delete last line

@echo off & setlocal EnableDelayedExpansion
set row=
for /F "delims=" %%j in (File.txt) do (
  if  defined row echo.!row!>> File.new
  set row=%%j
)

but wasn't helpful

Upvotes: 0

Views: 1420

Answers (3)

Adrian Nielsen
Adrian Nielsen

Reputation: 11

@echo off
setlocal enabledelayedexpansion
for /f %%a in (forward.txt) do (
     set reversed=%%a !reversed!
)
for %%i in (!reversed!) do echo.%%i >> reversed.txt
goto :eof

Upvotes: -1

Squashman
Squashman

Reputation: 14290

This is a Vbscript solution.

Create a file named reverse.vbs and use this as the code.

Dim Stack: Set Stack = CreateObject("System.Collections.Stack")

Do While Not WScript.StdIn.AtEndofStream
    Stack.Push WScript.StdIn.ReadLine
Loop

WScript.StdOut.WriteLine Join(Stack.ToArray, vbCrLf)

Now to reverse your file execute this from a cmd prompt or a batch file.

type input.txt |cscript //nologo Reverse.vbs>>output.txt

Upvotes: 1

Magoo
Magoo

Reputation: 80033

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "destdir=U:\destdir"
SET "filename1=100lines.txt"
SET "outfile=%destdir%\outfile.txt"
SET /a count=0
FOR /f "delims=" %%a IN (%filename1%) DO (
 SET /a count+=1
 SET "line[!count!]=%%a"
)
(
FOR /L %%a IN (%count%,-1,1) DO ECHO(!line[%%a]!
)>"%outfile%"

GOTO :EOF

You would need to change the setting of destdir to suit your circumstances.

I used a file named 100lines.txt containing some dummy data for my testing.

Produces the file defined as %outfile%

Using delayedexpansion, read each line into line[?] using !count!, then simply echo each line loaded in reverse order.

Upvotes: 3

Related Questions