我有一个问题。我有模仿UNIX cd命令的批处理文件。这需要由用户输入的UNIX风格的路径,将其保存为一个名为upath2变种,将其转换为Windows风格的路径,和CD到该目录(如“/程序文件/ 7-ZIP”将成为“C: \ Program Files文件\ 7-Zip的“)。在Windows般的输出将被保存为一个名为VAR和upath2 cmdcd命令将执行并切换到该目录。

随着这种“UNIX” cd命令,我也创建了一个叫做“bashemu.bat”的批处理文件,这给了我一个bash类似的提示。所有的命令都是DOSKEY条目,我创建了链接到bin和USR \ bin文件夹中,其容纳所有的蝙蝠命令。然后,它在最后执行“cmd / V / K”这样我就可以进入DOSKEY别名并启动所有的UNIX风格的命令。

现在,这里是我的问题:当我的CD-ING我的C的子目录:\用户\文件夹xplinux557 (存储在称为“unixhome”环境变量),提示符的bashemu更改自:

xplinux557@bash-pc:~$

,例如:

xplinux557@bash-pc:/Users/xplinux557/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$

这样的路径太长,要在命令提示符bashemu内舒适地使用,所以我试图让cd命令阅读完整upath2变量和检查,看看它是否包含主路(由unixhome定义),并简单地替换了〜。这应该关闭此:

xplinux557@bash-pc:/Users/xplinux557/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$

到该:

xplinux557@bash-pc:~/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$

AAAAH,好多了!我的第一个方法是UPATH的UNIX风格的路径转换为Windows风格的路径和名称的新变种upath2,并用“〜”替换文本%unixhome%。这是代码如何看起来像:

:: set the batch file to retrieve all text from its parameters and replace all
:: unix-style slashes the user put in and replace those with a windows-style backslash
@echo off
set upath=%*
set upath=%upath:/=\%

:: cd to the directory that the user typed in, windows-style
cd "%upath%"

:: Set the upath2 var to the current directory and replace whatever unixhome was
:: a "~"
set upath2=%cd:%unixhome%="~"%

:: Remove the "C:" or "D:" from the quote
set upath2=%upath2:~2%

:: then, set the prompt to read:
:: "xplinux557@bash-pc:~/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$"
prompt=%USERNAME%@%USERDOMAIN%:%upath2% $$ 

::EOF

一切工作完全正常,除了读取的行:

set upath2=%cd:%unixhome%="~"%

我意识到它弄乱和识别%CD:%和%=“〜”%作为变量和给我一个错误消息。我真的很抱歉,漫步在和这样的:),不过长话短说,有没有办法把变量A的文本,并替换文本如果变量B发现?

感谢大家提前!

有帮助吗?

解决方案

在延迟扩展依次用

setlocal enabledelayedexpansion

和使用

set upath2=!cd:%userprofile%=~!

请注意setlocal将开始一个新的变量范围和该范围内做不会存留在它之外的环境变量的任何改变。

可以,但是,做一次性使用以下内容:

setlocal enabledelayedexpansion
set upath2=!cd:%userprofile%=~!
endlocal&set upath2=%upath2%

其他提示

可以做一个 “EVAL” 使用CALL SET

:: This does not work:  set upath2=%cd:%unixhome%=~%

:: This works: 
:::: uhome is the homepath, with unix-style (forward) slashes 
set uhome=%HOMEPATH:\=/%
:::: ucwd is the current working directory, with unix-style (forward) slashes 
set ucwd=%cd:\=/%

:: replace any occurence of uhome in ucwd with ~
CALL SET ucwd=%%ucwd:%uhome%=~%%

:: strip drive letter and colon
set ucwd=%ucwd:~2%

:: set prompt
prompt=%USERNAME%@%USERDOMAIN%:%ucwd% $$

当我把这个我得到User@Machine:~/Documents/dev/batch

PS:我觉得你有一个bug。你不想%cd:...。你想与斜线的变量。

也:这不会是稳固的可靠。考虑这样你有一个目录结构类似这样的情况下:

  c:\Users\John\Other
  c:\Users\John\Other\Users
  c:\Users\John\Other\Users\John 
  c:\Users\John\Other\Users\John\data 

...在这种情况下,你将得到2个旋转因子。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top