如何用AppleScript-ObjC将磁盘挂载点路径的空格替换为转义反斜杠?
在AppleScript-ObjC中转义磁盘挂载点的空格
我通过以下命令获取磁盘挂载点:do shell script "diskutil info /dev/disk4s1 | sed -n 's/.*Mount Point: *//p'"
但当存在同名磁盘时,第二个磁盘的挂载点返回格式为:"/Volumes/myDisk 1"
我需要将其转换为带转义空格的格式:"/Volumes/myDisk\ 1"
实现方法
借助AppleScript-ObjC的NSString类提供的字符串替换方法,可以轻松完成空格转义:
use framework "Foundation" use scripting additions -- 获取原始挂载点 set rawMountPoint to do shell script "diskutil info /dev/disk4s1 | sed -n 's/.*Mount Point: *//p'" -- 转换为NSString并替换空格为转义格式 set nsMountPoint to current application's NSString's stringWithString:rawMountPoint set escapedMountPoint to nsMountPoint's stringByReplacingOccurrencesOfString:" " withString:"\\ " -- 添加上外层引号(如果需要) set finalResult to "\"" & (escapedMountPoint as text) & "\"" -- 输出结果 log finalResult
代码说明
- 首先通过
diskutil命令获取原始挂载点路径,路径中的空格未被转义。 - 将原始路径转换为
NSString对象,调用stringByReplacingOccurrencesOfString:withString:方法,把每个空格替换为\\(注意:在字符串中反斜杠需要双重转义,因此代码里写两个反斜杠)。 - 如果需要给结果添加上外层引号,直接通过字符串拼接实现即可。
内容的提问来源于stack exchange,提问作者TheOnlyOneHere
相关产品推荐
相关产品推荐

