Reputation: 71
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
Upvotes: 6
Views: 13259
Reputation: 137
One of the big issues in Batch is building ordered arrays, which has to be done via files, Batch doesn't have an array construct in it. One option you can do to force things into memory and save some IOPS in batch is use a ramdisk, making sure to abstract the filepaths into variables.
Upvotes: -1
Reputation: 1557
you can try using the code below.
@ECHO OFF
:: Store the string you want to prepend in a variable
SET "text=%1"
:: copy the contents into a temp file
type userlist.txt > temp.txt
:: Now Overwrite the file with the contents in "text" variable
echo %text% > userlist.txt
:: Now Append the Old Contents
type temp.txt >> userlist.txt
:: Delete the temporary file
del temp.txt
Hope this solves your problem. :)
Upvotes: 2
Reputation: 175
First, read the contents of the file. Append that to what you want to add to the beginning and write all of that to the file.
Upvotes: -2
Reputation: 484
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
Upvotes: 8
Reputation: 26150
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
Upvotes: 2