如何获取可区分重复文件名的最短唯一后缀路径
生成最短唯一文件路径后缀(R实现)
给定一组唯一的完整文件路径,我们需要为每个路径生成最短的后缀路径,使得所有生成的后缀都是唯一的——同名文件需要向上截取父目录直到路径唯一,唯一文件名直接返回自身。
需求示例
输入路径:
have <- c("/A/B/C/D", "/A/B/D", "/A/C/D", "/path/to/unique_file", "/path/to/another_unique_file", "/path/diverges/here/file", "/path/diverges/here1/file")
期望输出:
want <- c("B/C/D", "B/D", "A/C/D", "unique_file", "another_unique_file", "here/file", "here1/file") length(unique(want)) == length(have) # [1] TRUE
解决方案(Base R实现)
我们可以通过按文件名分组→逆向截取路径片段→验证唯一性的流程实现:
1. 定义核心处理函数
这个函数负责处理单个文件名分组,为组内每个路径生成最短唯一后缀:
get_shortest_unique_suffix <- function(paths) { # 单文件分组直接返回文件名 if (length(paths) == 1) { return(basename(paths)) } # 拆分路径为目录片段,过滤空字符串(处理路径开头的/) path_parts <- lapply(paths, function(p) { parts <- strsplit(p, "/")[[1]] parts[parts != ""] }) # 对每个路径,从末尾逐步截取片段直到唯一 sapply(seq_along(path_parts), function(i) { current_parts <- path_parts[[i]] # 从取1个片段(文件名)开始,逐步增加 for (k in 1:length(current_parts)) { suffix_parts <- tail(current_parts, k) suffix <- paste(suffix_parts, collapse = "/") # 检查当前后缀在组内是否唯一 all_suffixes <- sapply(path_parts, function(pp) paste(tail(pp, k), collapse = "/")) if (sum(all_suffixes == suffix) == 1) { return(suffix) } } # 兜底:原路径唯一,截取全部片段必然唯一 paste(current_parts, collapse = "/") }) }
2. 分组处理并合并结果
# 按文件名分组 path_groups <- split(have, basename(have)) # 对每个分组应用函数,合并结果 result <- unlist(lapply(path_groups, get_shortest_unique_suffix)) # 还原为原输入的顺序 result <- result[match(have, names(result))] # 查看结果 print(result) # 输出: # /A/B/C/D /A/B/D /A/C/D /path/to/unique_file /path/to/another_unique_file # "B/C/D" "B/D" "A/C/D" "unique_file" "another_unique_file" # /path/diverges/here/file /path/diverges/here1/file # "here/file" "here1/file" # 验证唯一性 length(unique(result)) == length(have) # [1] TRUE
说明
- 兼容不同深度的目录:比如示例中同名的
D文件在不同层级,函数会自动截取足够的父目录保证后缀唯一 - 完全基于Base R实现,无需额外安装包
- 原路径本身是唯一的,因此函数总能找到唯一后缀,不会出现无结果的情况
内容的提问来源于stack exchange,提问作者LMc
相关产品推荐
相关产品推荐

