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

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

Philip

Posted 2017-11-29T09:43:36.807

Reputation: 596

Don't use a static value for the target file but instead a (counting) variable or split the result by line break. – Seth – 2017-11-29T10:15:42.833

Answers

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

DavidPostill

Posted 2017-11-29T09:43:36.807

Reputation: 118 938

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 – 2017-11-29T16:33:59.183

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

dbenham

Posted 2017-11-29T09:43:36.807

Reputation: 9 212