how to separate single text file into multiple text file by lines using batch?

I have running the following program,

@echo off
cls
set /p "filename=type file name>"
setlocal enabledelayedexpansion
for /r E:\ %%a in (*) do if "%%~nxa"=="%filename%" (
echo %%~dpnxa >>path.txt
)

I have got a output file path.txt which contains,

E:\new.txt
E:\Redmi\new folder\new.txt
E:\windows\new folder\new folder\new.txt

I like to have those in separate files like,

E:\new.txt in path1.txt

E:\Redmi\new folder\new.txt in path2.txt

E:\windows\new folder\new folder\new.txt in path3.txt

1

2 Answers

How can I separate single text file into multiple text file by lines?

Building on the comment by Seth, you can use the following batch file:

@echo off
cls
setlocal enabledelayedexpansion
set /p "filename=type file name>"
rem initialise counter to 1
set _count=1
for /r E:\ %%a in (*) do if "%%~nxa"=="%filename%" ( echo %%~dpnxa >>path!_count!.txt rem increment the counter set /a _count+=1 )
endlocal

Notes:

  • I have moved the setlocal line in order to stop the variable filename leaking into the calling cmd shell.

Further Reading

1

I have a much simpler, and probably faster solution for you:

  • Use DIR /S /B /A-D instead of FOR /R to get the path list. This eliminates the need for an IF statement.
  • Pipe to FINDSTR /N, matching on the beginning of a line, to get the line number for use in output file name.
  • Execute the entire thing within FOR /F to iterate and parse the results into the line number and the path of each line.
@echo off
setlocal
set /p "filename=type file name>"
for /f "delims=: tokens=1*" %%A in ( 'dir /s /b /a-d "E:\%filename%" ^| findstr /n "^"'
) do >"path%%A.txt" echo %%B

If it were my script, I would pass the target filename as an argument rather than prompt for it:

@echo off
for /f "delims=: tokens=1*" %%A in ( 'dir /s /b /a-d "E:\%~1" ^| findstr /n "^"'
) do >"path%%A.txt" echo %%B

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like