Recursively Search for Text file and Edit

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Danny
Posts: 15
Joined: 30 Oct 2013 22:52

Recursively Search for Text file and Edit

#1 Post by Danny » 30 Oct 2013 23:27

Hello,

I need to search for text file [.txt] in directories and delete the first line from multiple text files inside them.
Folder structure : Root folder ---> Folders from 001 to 100, recursively search range of folders only, please don't edit other folders text files except this (from 001 to 100) and delete the first line of this text files.

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Recursively Search for Text file and Edit

#2 Post by ShadowThief » 31 Oct 2013 00:05

Is the folder structure
/root/001
/root/002
/root/003
...
/root/100

or is it

/root/001/002/003/.../100 ?

Danny
Posts: 15
Joined: 30 Oct 2013 22:52

Re: Recursively Search for Text file and Edit

#3 Post by Danny » 31 Oct 2013 00:57

Hi,

This structure:
/root/001
/root/002
/root/003
...
/root/100

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Recursively Search for Text file and Edit

#4 Post by foxidrive » 31 Oct 2013 01:38

Are there any other folders like this in the root:

\root\apple
\root\pear
\root\001
\root\002
\root\003
...
\root\100
\root\zulu

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: Recursively Search for Text file and Edit

#5 Post by ShadowThief » 31 Oct 2013 02:56

Pass the name of the root folder in as a parameter and you should be good to go, provided you don't have any exclamation points in your filenames.

Code: Select all

:5043.bat <root_dir>
:: Searches for folders labelled 001 through 100 in /root_dir, takes all text
:: files inside those directories, and removes the first line, leaving the rest
@echo off
setlocal enabledelayedexpansion

if [%1]==[] echo Please enter a directory.&goto :eof
if not exist %1 echo Please enter a directory.&goto :eof
set root_dir=%1
pushd %root_dir%

:: That's a lot of nested for loops. There's almost certainly a better way, but
:: hopefully I'm at least close.
for /l %%Z in (1,1,100) do (
   set num=%%Z
   if !num! lss 10 set "num=0!num!"
   if !num! lss 100 set "num=0!num!"
   
   pushd !num!
   
   for /f %%X in ('dir /b *.txt') do (
      for /f "skip=1 tokens=1 delims=" %%A in ('findstr /n "^" "%%X"') do (
         for /f "tokens=1,2 delims=:" %%C in ("%%A") do if [%%D]==[] (echo.) else (echo %%D)
      )>>new_%%X
      move new_%%X %%X >nul
   )
   popd
)

Post Reply