如何在SAS中从File_Path变量提取目录路径(排除文件名)
在SAS中提取文件路径的目录部分(排除文件名)
针对你的需求,这里提供两种可行的SAS实现方法:
方法1:字符串处理函数(推荐,直接高效)
利用SAS的字符串查找与截取函数,定位路径中最后一个斜杠/的位置,截取该位置之前的部分即可得到目录路径:
data want; set have; /* 从字符串末尾反向查找最后一个斜杠的位置 */ last_slash = find(File_Path, '/', -length(File_Path)); /* 截取从开头到最后一个斜杠的所有字符,保留末尾斜杠 */ dir_path = substr(File_Path, 1, last_slash); run;
逻辑说明
find(File_Path, '/', -length(File_Path)):第三个参数为负数时,函数从字符串末尾开始正向查找第一个/,返回该字符的位置。substr(File_Path, 1, last_slash):截取字符串从第1位到最后一个斜杠的位置,得到带末尾斜杠的完整目录路径,与你期望的输出格式完全匹配。
方法2:利用SAS文件系统函数
通过临时关联文件路径到逻辑名,调用pathname函数提取目录:
data want; set have; /* 将当前File_Path关联到临时逻辑名temp_file */ filename temp_file "&File_Path"; /* 提取目录路径 */ dir_path = pathname(temp_file); /* 清理临时逻辑名,避免冲突 */ filename temp_file clear; run;
注意事项
- 如果路径包含空格或特殊字符,需要确保宏变量解析正确,可将
&File_Path用双引号包裹:filename temp_file "&File_Path"; - 该方法无需文件实际存在,仅解析路径字符串即可生效。
示例验证
针对你提供的输入路径,两种方法处理后均会输出:
/start_file_pth/data/sg/prod5/file_path/ /start_file_pth/data/lrstr/sg/prod5/location/ /start_file_pth/data/lrstr/hk/prod89/test/ /start_file_pth/data/lrstr/testing/hk/prod5/
内容的提问来源于stack exchange,提问作者vmaha13
相关产品推荐
相关产品推荐

