首页 > 解决方案 > Cut first line in text file and paste into another file

问题描述

I need a batch file to cut the first line of a file1.txt, save this file, paste the line to file2.txt and save this second file; in particular I want it to overwrite the second file, here's an example

File1.txt:

line 1
line 2
line 3
line 4

File2.txt is empty. I want to transfer the first line to the second file so that

File1.txt

line 2
line 3
line 4

And File2.txt will be:

line 1

Save both files. When I run the batch file again, I want it to overwrite the second file so that:

File1.txt

line 3
line 4

And File2.txt will be:

line 2

标签: batch-filetext-files

解决方案


这可以通过以下方式实现:

@echo off

set "file1=file1.txt"
set "file2=file2.txt"

goto :first_loop

:first_loop
for /F "delims= eol=" %%A IN ('type "%file1%"') do (
    (echo %%A)>"%file2%"
    goto :second_loop
)

:second_loop
for /F "skip=1 delims= eol=" %%A IN ('type "%file1%" ^& del "%file1%"') do (echo %%A)>>"%file1%"
if not exist "%file1%" (type nul >%file1%)
goto :completion

:completion
echo Completed!
pause>nul
exit /b

实际上,在第一个循环中,您echo将第一行添加到第二个文件,而在第二个循环中,您实际上删除了第一个文件的第一行。

看:

  • for /?
  • type /?
  • del /?
  • echo /?
  • goto /?

了解更多信息。


推荐阅读