- 帖子
- 56
- 积分
- 69
- 技术
- 1
- 捐助
- 0
- 注册时间
- 2016-10-21
|
本帖最后由 huyou96 于 2016-10-23 10:44 编辑
回复 4# aa77dd@163.com
再请教您一下字符串截取的问题,我这里运行 echo;"%~dp0" 的结果如下:
"C:\Users\Huyou\Documents\"
但我想要去掉该字符串最后一个反斜杠字符,就是说我想要echo输出的格式如下:
"C:\Users\Huyou\Documents"
请问我该如何做?
(曾按论坛的截取字符串的简单例子
set str=123456789
echo 去掉最后一个字符后的字符串为:%str:~0,-1%,
试验过 echo "%(%%~dp0%):~0,-1%"
但一试就失败了,输出结果是:"C:\Users\Huyou\Documents\~0,-1"
还试了 echo "%(%%~dp0%:~0,-1%)%"
输出结果是:"C:\Users\Huyou\Documents\:~0,-1"
好失败啊
)
补充:还是我太菜了。
明白了,原来不必想得那么复杂,只消 echo %0 输出结果就是不带反斜杠的"C:\Users\Huyou\Documents"
而echo "%~dp0" 结果是带反斜杠的 "C:\Users\Huyou\Documents\"
是我太笨了,总想不明白……
再补充,到晚上就糊涂了,刚才的还是错了。要写到只有一行就显示出 "C:\Users\Huyou\Documents" 不带反斜杠的路径结果,我的水平只能多设置一步变量写成如下这样:
set mydir="%~dp0" && echo %mydir:~0,-1%
不知其他大虾有没有其他更好的方法?
再再补充:昨晚还是设置变量菜了,path是系统环境变量不该用于批处理里,因会导致系统环境变量更改重置,故修改为mydir,这样就OK了。
还在批处理里用xcopy、copy么,你out啦,新写脚本都该采用鲁棒拷贝robocopy,带用参数连时间戳等等都能保留,拷贝文件夹或文件都强大又好用,唯一值得注意地方是无论拷贝文件还是拷贝文件夹,作为来源或目标文件夹参数的路径里不能带有最末字符反斜杠,否则执行时会报错。只消把路径里最后一个反斜杠去掉即可。
像如下这样就都会报错:
✖ robocopy "C:\Users\Huyou\Downloads\" "C:\Users\Huyou\Documents\"
✖ robocopy "C:\Users\Huyou\Downloads\" "C:\Users\Huyou\Documents"
✖ robocopy "C:\Users\Huyou\Downloads" "C:\Users\Huyou\Documents\" mytest.bat
✖ robocopy "%HomePath%\Downloads\" "%HomePath%\Documents\"
✖ robocopy "%~dp0" "%UserProfile%\Documents" mytest.bat
正确的,应该如下这样子:
✔ robocopy "C:\Users\Huyou\Downloads" "C:\Users\Huyou\Documents"
✔ robocopy "C:\Users\Huyou\Downloads" "C:\Users\Huyou\Documents" "mytest.bat"
✔ robocopy "%UserProfile%\Downloads" "%UserProfile%\Documents"
✔ set mydir=%~dp0 && robocopy "%mydir:~0,-1%" "%HomePath%\Documents" mytest.bat |
|