Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add to beginning using text file using a .bat instead of append to end?

Tags:

batch-file

I have a batch file that returns a list of data. Currently, every time I run the script, it appends the newly pulled data to the end of the text file. Is there a way that I can add the new data to the beginning of the file, rather than append it to the end? I need to it work this way because the data is pulled chronologically, and I'd like the text file to be sorted from most recent to oldest.

@ECHO OFF

REM Used to log server users stats into a text file located in the local c:\userlog directory

ECHO Terminal Server Users, %Date%, %TIME%>>c:\Userlogs\UserListTest.txt
quser /server:servername>>C:\Userlogs\UserListTest.txt

START C:\Userlogs\UserListTest.txt
Exit

any help will be greatly appreciated

like image 860
Matt Avatar asked Jan 14 '23 08:01

Matt


2 Answers

Following will work as you want

    echo this will come at the begining of file >>log.txt
    type log1.txt >> log.txt
    del log1.txt
    ren log.txt log1.txt
like image 191
Shirulkar Avatar answered May 20 '23 18:05

Shirulkar


one way using temporary file.

prepend.bat :

:: copy existing file to a temporary file
copy c:\temp\existing.txt c:\temp\temp.txt
:: replace content with your new value
echo test >c:\temp\existing.txt
::  append content of temp file
for /F %%i in (c:\temp\temp.txt) do echo %%i >> c:\temp\existing.txt
:: remove tempfile
del c:\temp\temp.txt
like image 27
Loïc MICHEL Avatar answered May 20 '23 19:05

Loïc MICHEL