windows - 编写脚本以在批处理脚本中递归列出其中的目录和文件
问题描述
我正在尝试编写一个批处理脚本,该脚本以以下格式递归列出所有目录及其文件:*.js
例如,如果我从C:\project
目录开始
c:\project
project.js
project_time.js
c:\project\core
core.js
core_render.js
core_application.js
我尝试在代码中实现上述逻辑,如下所示:
@echo off
for /r %%f in (*.js) do (
echo %%f >> names.txt
)
pause
我无法打印列出文件的目录。
解决方案
@echo off
setlocal disabledelayedexpansion
set "lastdir="
( for /r %%A in (*.js) do (
set "nextdir=%%~dpA"
setlocal enabledelayedexpansion
if /i not "!lastdir!" == "!nextdir!" (
rem Empty line and directory path.
if defined lastdir @echo(
@echo !nextdir!
)
endlocal
rem Filename.
@echo %%~nxA
set "lastdir=%%~dpA"
)
) > "names.txt"
The lastdir
variable is to record the last directory path so it is echoed only once.
If lastdir
is different to %%~dpA
:
- If
lastdir
is defined, then an empty line will be echoed. - Directory path of found file is echoed.
Filename is always echoed.
for
modifiers dp
is the drive and path. nx
is the name and extension.
setlocal enabledelayedexpansion
is used only where needed so paths with !
are not vulnerable.
I am not going to suggest a command line solution as it would be very long. Instead suggest use of tree
command if the output format is suitable.
推荐阅读
- javascript - 反应路由器和滚动行为
- java - 使用spring cloud stream在kafka中自动提交
- java - SSL Principal Mapping in Kafka
- git - 如何找出在 Git 钩子期间被推送到哪个分支?
- flutter - 如何在 Flutter 的 dart 中绘制具有坐标系(例如 Sin(x))的 2d 函数?
- c++ - 使用 cgal 和 pcl 时的链接错误提升
- powershell - 要求进行代码审查:PowerShell 对本地 PC 而不是 $inventory 中所需的远程 PC 执行多次
- excel - 运行宏时循环宏公式不起作用
- hive - 用于 Hive 插入查询的 ConvertJsonToSQL
- flutter - 使用另一个类的列表值