Board logo

标题: [文件操作] [分享]批处理往上取3层的目录 [打印本页]

作者: Batcher    时间: 2023-8-21 17:48     标题: [分享]批处理往上取3层的目录

【问题描述】
  1. @echo off
  2. setlocal enabledelayedexpansion
  3. set p=C:\Users\farben\AppData\Roaming\DBeaverData\workspace6\General\Scripts
  4. for /l %%b in (1,1,3) do (
  5.     for %%c in (!p!) do (
  6.         set p=%%~dpc
  7.         set p=!p:~0,-1!
  8.         echo,!p!
  9.     )
  10. )
  11. pause
复制代码
写了个递归取上级目录
不知道 有没有更好的方法
你们一般遇到这种往上取3层的目录怎么实现呢?
作者: Batcher    时间: 2023-8-21 17:48

【解决方案】
  1. @echo off
  2. set "p=C:\Users\farben\AppData\Roaming\DBeaverData\workspace6\General\Scripts"
  3. for %%i in ("%p%\..\..\..") do (
  4.     echo,%%~fi
  5. )
  6. pause
复制代码

作者: Nsqs    时间: 2023-8-21 20:46

我之前用PowerShell写了一个,调用PowerShell一层for就能出来了,帖子在哪里不记得了
作者: Nsqs    时间: 2023-8-21 21:39

本帖最后由 Nsqs 于 2023-8-21 21:47 编辑
  1. @echo off
  2. powershell -noprofile -executionpolicy bypass "&{param([string]$Path='.',[int]$Return=0);$CurrentPath=[System.IO.DirectoryInfo]::new($Path).FullName;if($Return -eq 0){return $CurrentPath};$Count=[regex]::Matches($CurrentPath,'\\').Count;if($Count -lt $Return){throw '无法返回更多层了!'};$Layer=$Count-$Return;if($Layer -eq 0){$Layer=1};$CurrentPath.Substring(0,$CurrentPath.IndexOf('\',$Layer+1))}" -return 2
  3. pause
复制代码
参数-path可以指定路径 -return指定返回的层数,上面写2表示返回2层
作者: Nsqs    时间: 2023-8-21 21:55

  1. (dir ..\.. -Directory).Parent.FullName
复制代码
虽说这样也行,但是不能按数字来准确指定向上一级返回多少层
作者: Nsqs    时间: 2023-8-21 22:21

p版的思路
  1. @echo off
  2. call:redir 2
  3. pause
  4. goto :eof
  5. :redir
  6. set "s=..\"
  7. set /a return=%1
  8. for /l %%1 in (1,1,%return%)do (
  9. call set "s=%%s%%..\"
  10. )
  11. for %%1 in (%s%)do echo %%~f1
  12. goto :eof
复制代码

作者: Five66    时间: 2023-8-22 00:55

额,这让我想起第一次看见"D:\aaa\bbb.txt\..\ccc.txt" 这样的路径,脑袋卡壳,想半天才发现的两个点(..)所说的的“上一级目录”不仅仅是“当前目录”的“上一级目录” 的事情
作者: jszw666    时间: 2023-8-22 09:18

做个标记,留存学习。楼主辛苦了!




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2