A batch that interchanges the first and last lines

Time:2021-1-21

Then write the extracted last line in the first line of the new text, filter out the first line and the last line of the original text with findstr statement, and add the extracted first line after the last line.

Copy codeThe code is as follows:
@echo off
Purpose: to swap the first and last lines
Idea:
: extract the contents of the first line and the last line (if the first line and the last line are empty lines, the contents of the first line and the last line that are not empty will be extracted),
: then write the extracted last line in the first line of the new text, and filter out the first and last lines of the original text with findstr statement
:: and then add the first line to extract to.
: because findstr has conditional restrictions on processing the last line, an empty line is generated after the last line to ensure the accuracy of extraction
Note: please make sure test.txt There are no sensitive characters, no duplicate lines, and the first line cannot be empty
::    
::     
copy test.txt test.bak>nul
echo.>>test.txt
set num=0
setlocal enabledelayedexpansion
for /f “delims=” %%i in (test.txt) do (
set str=%%i
set /a num+=1
if !num! equ 1 set var=%%i
)
>test_.txt echo.%str%
findstr /b /e /v /c:”%str%” /c:”%var%” test.txt>>test_.txt
>>test_.txt echo.%var%
move test.bak test.txt
start test_.txt
goto :eof

@echo off
: it can handle the situation that the first line is empty and the content of the line is repeated,
: Note: because when findstr / N counts the number of rows, the last empty row will be ignored
: therefore, if there are blank lines at the end, please ensure that the number of blank lines is greater than 1
findstr /n .* test.txt>tmp1.txt
for /f “tokens=1* delims=:” %%i in (tmp1.txt) do (
if %%i equ 1 set str=%%j
set line=%%i&set var=%%j
)
>tmp2.txt echo %line%:%var%
findstr /b /v /c:”1:” /c:”%line%:” tmp1.txt>>tmp2.txt
echo 1:%str%>>tmp2.txt
echo.>>tmp2.txt
cd.>result.txt
for /f “tokens=1* delims=:” %%i in (tmp2.txt) do >>result.txt echo.%%j
del /q tmp1.txt tmp2.txt
start result.txt