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

如何删除文件路径中指定目录及之前部分,获取目录之后的剩余路径

实现思路
  • 先将输入的完整路径按路径分隔符/切割为目录片段数组,过滤掉切割产生的空字符串,避免路径首尾的/生成无效空片段
  • 在目录片段数组中查找指定目录名对应的下标位置
  • 若未找到指定目录,可根据业务需求选择返回原路径、抛出异常或返回空值
  • 取下标位置之后的所有目录片段,重新拼接为路径,首尾补充/即可得到目标结果

注意:如果路径中存在多个同名的指定目录,下述实现默认取第一个出现的目录为截断点;如果需要取最后一个出现的目录为截断点,将查找索引的方法替换为反向查找即可。

各语言实现示例

Python 实现

def trim_path_left(full_path: str, target_dir: str) -> str:
    # 切割路径并过滤空片段
    path_parts = [part for part in full_path.split('/') if part]
    try:
        target_index = path_parts.index(target_dir)
    except ValueError:
        # 未找到指定目录时返回原路径,可按需调整逻辑
        return full_path
    # 拼接截断后的路径,首尾补充/
    return '/' + '/'.join(path_parts[target_index + 1:]) + '/'

调用测试:
trim_path_left('/var/www/sei/modules/module1/', 'sei')
返回结果:/modules/module1/

JavaScript 实现

function trimPathLeft(fullPath, targetDir) {
    const pathParts = fullPath.split('/').filter(part => part.length > 0)
    const targetIndex = pathParts.indexOf(targetDir)
    // 未找到指定目录时返回原路径
    if (targetIndex === -1) return fullPath
    return '/' + pathParts.slice(targetIndex + 1).join('/') + '/'
}

Bash 实现

trim_path_left() {
    local full_path="$1"
    local target_dir="$2"
    echo "$full_path" | awk -F/ -v tgt="$target_dir" '
    {
        found = 0
        res = ""
        for (i = 1; i <= NF; i++) {
            if ($i == tgt) {
                found = 1
                continue
            }
            if (found == 1 && $i != "") {
                res = res "/" $i
            }
        }
        print res "/"
    }'
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:06:03