简体   繁体   中英

Searching for files in a directory and sub-directories and editing specific lines within those files

Searching for files in a directory and sub-directories and editing specific lines within those files.

C:\Users\user\Desktop\backup>dir
Volume in drive C has no label.
Volume Serial Number is C8D8-4C1B

Directory of C:\Users\user\Desktop\backup

02/13/2017  03:02 PM    <DIR>          .
02/13/2017  03:02 PM    <DIR>          ..
02/13/2017  02:21 PM    <DIR>          blog
02/13/2017  02:21 PM    <DIR>          css
02/13/2017  02:21 PM    <DIR>          forgot
02/13/2017  02:21 PM    <DIR>          img
02/13/2017  02:21 PM            13,845 index.htm
02/13/2017  02:21 PM    <DIR>          pages
02/13/2017  02:21 PM    <DIR>          photo
02/13/2017  02:21 PM    <DIR>          photos
02/13/2017  02:21 PM    <DIR>          profile
02/13/2017  02:21 PM    <DIR>          signin
02/13/2017  03:11 PM                89 test.bat
02/13/2017  02:21 PM    <DIR>          theme
02/13/2017  02:21 PM    <DIR>          view
2 File(s)         13,934 bytes
13 Dir(s)  74,300,223,488 bytes free

I've searched on stackoverflow for answers and found this code:

for /R %f in (index.htm)" do "x"

and

findstr /v /i "body" index.htm > indexnew.htm

I came up with and failed with this code:

"for /R %f in (index.htm)" do "findstr /v /i "shaw" index.htm >     indexnew.htm"

pause

It fails.

I need to manipulate files in main directory and sub-directories with the name index.htm to delete specific lines or lines with the word "shaw" within them.

  1. You are placing useless quotation marks " at odd positions -- do not do that!
  2. Double the % sign when using for loops in a batch file, like for /R %%f .
  3. for /R does not actually search for matching files when there is no global wild-card like * or ? ; so it is better to use for /F "delims=" %%f in ('dir /B /S "index.htm"') do ... .
  4. Simply place the findstr command line into the body of the for loop and use the for variable reference %%f as the file name.
  5. Use redirection to write the output of a command into a file; but you cannot specify the same file that is already processed by the command, so you need to use a temporary file and move it onto the original one afterwards.

All this means:

for /F "delims=" %%f in ('dir /B /S "index.htm"') do (
    findstr /V /I /C:"shaw" "%%~f" > "%%~f.tmp"
    move /Y "%%~f.tmp" "%%~f" > nul
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM