Jerry
Jerry

Reputation: 1

Batch to delete older lines

I have a txt file which contains a series of data like this

   Date      Time          Id    Set
2020/05/04 15:22:28      10005   4512
2020/05/04 15:23:47      10005   4528
2020/05/04 15:23:48      10005   4543
2020/05/04 15:23:58      10005   4555
2020/05/04 15:24:00      10005   4533
2020/05/04 15:24:03      10005   4512
2020/05/04 15:24:05      10005   4590

I need to delete the oldest lines based on the writing time, how can I get this final result in the txt file?

2020/05/04 15:24:05      10005   4590

Sorry for my ability, I'm trying

    powershell.exe -Command get-content "D:\filelog.txt" | where { [datetime]($_.split(','))[0] -ge (get-date).date.adddays(-30)} 
set-content "D:\Newfilelog.txt"

Obviously I'm wrong, since it doesn't work

Upvotes: 0

Views: 56

Answers (2)

Magoo
Magoo

Reputation: 80033

'Tis an ancient question, but since, given the data, what is required is the first line (header) and last,

(
 set "line="
 for /F "delims=" %%L in (input.txt) do (
 if not defined line echo %%L
 set "line=%%L"
 )
 echo %line%
)>"output.txt"

The enclosing parentheses allow the echo output to be redirected to the file.

Otherwise, force line to be undefined, then echo the first line as line is then undefined, and thenassign the data read to line

When the reading is finished, the last line is in line, so echo it.

Upvotes: 1

aschipfl
aschipfl

Reputation: 34919

Sort the data in ascending order and read the last line:

rem /* Sort the data in ascending (alphabetic) order, excluding the first line;
rem    then loop through the sorted lines: */
for /F "delims=" %%L in ('more +1 "input.txt" ^| sort') do (
    rem /* Store the current (non-empty) line; this value overwritten in each iteration,
    rem    so eventually the last line is stored in the variable: */
    set "LAST=%%L"
)
rem // Read the first line (header) of the data:
< "input.txt" (set "FIRST=" & set /P FIRST="")
rem // Return the gathered information (first and last lines):
if defined LAST (
    > "output.txt" (
        echo %FIRST%
        echo %LAST%
    )
)

Upvotes: 0

Related Questions