1

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

  • Don't use a static value for the target file but instead a (counting) variable or split the result by line break. – Seth Nov 29 '17 at 10:15
1

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
    As written, this will fail if any part of an output path includes an exclamation point. The solution requires toggling of delayed expansion ON and OFF within the loop. But I prefer to use FINDSTR /N coupled with FOR /F to get the line numbers without the need for delayed expansion (see my answer). – dbenham Nov 29 '17 at 16:33
2

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.