FORFILES批量删除特定后缀超过一周的文件

FORFILES批量删除特定后缀超过一周的文件

我想批量使用 FORFILES 删除localhost_access_log一周前的文件(不是子目录),但我发现%%t was unexpected at this time.

for %%t in (.txt) do forfiles /p "C:\Program Files\Apache Software Foundation\Tomcat 8.0\logs\" /s /m *%%t /d -10 /c "cmd /c del @PATH"

答案1

for /f useback^tokens^=* %i in (`2^>nul forfiles /p "C:\Program Files\Apache Software Foundation\Tomcat 8.0\logs\" /s /m "*.txt" /d -10 /c "cmd /c echo=@Path"`)do @echo\%~ni|findstr/bil localhost_access_log >nul && echo\ del/q /f "%~fi"

1.无效掩码位于:/m *%%t

%%t是一条完整路径,它是上一个循环的结果,且 100% 合格,但不是 使用的掩码forfiles,即使添加到*,则不会将其作为掩码处理。

2.您可以更换/m *%%t到:

/m "*.txt"

3.替换ForFor /F循环:

for /f useback^tokens^=* %i in (`2^>nul forfiles /p "C:\Program Files\Apache Software Foundation\Tomcat 8.0\logs\" /s /m "*.txt" /d -10 /c "cmd /c echo=@Path"`)do ...

4.使用echo\FileName检查它是否与要删除的文件的名称匹配,使用|重定向Findstr,以及操作员&&return 0) 执行del如果名称匹配:

@echo\%~ni|findstr/bil localhost_access_log >nul && echo\ del /q /f "%~i"

5.测试并确认是否满意,若满意,则删除echo以有效删除该文件。

@echo\%~ni|findstr/bil localhost_access_log >nul && del /q /f "%~i"

观察:- 使用For循环可以扩展变量:

    %~i   - expands %i removing any surrounding quotes (")
    %~fi  - expands %i to a fully qualified path file/dir name only
    %~ni  - expands %i to a file/dir name only
    %~xi  - expands %i to a file/dir extension only
    
    %%~nxi => expands %%~i to a file/dir name and extension
  • Use the FOR variable syntax replacement:
        %~pI        - expands %I to a path only
        %~nI        - expands %I to a file name only
        %~xI        - expands %I to a file extension only
  • The modifiers can be combined to get compound results:
        %~pnI       - expands %I to a path and file name only
        %~pnxI      - expands %I to a path, file name and extension only

其他资源:

相关内容