You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nim语言:如何获取路径中倒数第二个/的索引以提取目录名

解决Nim中提取倒数第二级目录名的问题

方法一:手动字符串处理(适配Unix风格路径)

如果你的路径统一使用/作为分隔符,可以通过两次rfind()定位倒数第二个分隔符,提取目标目录名:

proc getSecondLastDir(path: string): string =
  let lastSlash = path.rfind('/')
  if lastSlash == -1:
    return ""
  # 截取最后一个/之前的路径部分
  let parentPath = path[0..<lastSlash]
  let secondLastSlash = parentPath.rfind('/')
  if secondLastSlash == -1:
    # 路径仅含一级目录,比如"PEOPLE/file.csv"
    return parentPath
  # 提取两个/之间的目录名
  result = parentPath[secondLastSlash+1..^1]

# 测试示例
echo getSecondLastDir("/data/PEOPLE/file1.csv")  # 输出: PEOPLE
echo getSecondLastDir("/docs/SALES/report.csv")  # 输出: SALES

方法二:使用标准库os模块(跨平台推荐)

Nim的os模块提供原生路径处理函数,自动适配不同系统的路径分隔符(Unix的/、Windows的\),稳定性更强:

import os

proc getSecondLastDir(path: string): string =
  # 拆分路径为「父目录」和「文件名」
  let (parentDir, _) = splitPath(path)
  # 再次拆分父目录,得到「祖父目录」和「目标目录」
  let (_, targetDir) = splitPath(parentDir)
  result = targetDir

# 跨平台测试
echo getSecondLastDir("/data/PEOPLE/file1.csv")       # 输出: PEOPLE
echo getSecondLastDir("C:\\docs\\SALES\\report.csv")  # 输出: SALES

结合递归遍历实现文件分组

将目录提取逻辑与递归遍历结合,用Table存储分组后的文件列表:

import os, tables

# 存储分组:目录名 -> 对应文件路径列表
var fileGroups = initTable[string, seq[string]]()

proc traverseAndGroup(dir: string) =
  for entryKind, entryPath in walkDir(dir):
    if entryKind == pcFile:
      let groupName = getSecondLastDir(entryPath)
      if groupName.len > 0:
        # 初始化分组列表(如果不存在)
        if groupName not in fileGroups:
          fileGroups[groupName] = newSeq[string]()
        fileGroups[groupName].add(entryPath)
    elif entryKind == pcDir:
      # 递归遍历子目录
      traverseAndGroup(entryPath)

# 替换为你的根目录路径
traverseAndGroup("/your/target/root/dir")

# 打印分组结果
for groupName, files in fileGroups:
  echo "* 分组: ", groupName
  echo "  文件列表: ", files

内容的提问来源于stack exchange,提问作者Bor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:42:26