Eya*_*ron 5 cmd batch-file command-prompt
我有个问题.我有一个模拟UNIX cd命令的批处理文件.它采用用户输入的UNIX风格路径,将其保存为名为upath2的var,将其转换为Windows风格的路径,然后cd转到该目录(例如"/ program files/7-zip"将变为"C:\Program Files\7-Zip").在Windows般的输出将被保存为一个名为VAR和upath2 cmd的cd命令将执行并更改到该目录.
除了这个"UNIX"cd命令,我还创建了一个名为"bashemu.bat"的批处理文件,它给了我类似bash的提示.所有命令都是doskey条目,它链接到我创建的bin和usr\bin文件夹,它们包含所有.bat命令.然后它在末尾执行"cmd/v/k",这样我就可以输入doskey别名并启动所有UNIX样式的命令.
现在,这是我的问题:当我进入我的C:\ Users\xplinux557文件夹的子目录(存储在名为"unixhome"的环境变量中)时,bashemu的提示符改变自:
xplinux557@bash-pc:~$
Run Code Online (Sandbox Code Playgroud)
举例来说:
xplinux557@bash-pc:/Users/xplinux557/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$
Run Code Online (Sandbox Code Playgroud)
像这样的路径太长,无法在命令提示符中的bashemu中使用,所以我试图让cd命令读取完整的upath2变量并检查它是否包含主路径(由unixhome定义)并简单地用〜替换它.这应该转为:
xplinux557@bash-pc:/Users/xplinux557/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$
Run Code Online (Sandbox Code Playgroud)
进入这个:
xplinux557@bash-pc:~/Documents/MacSearch_v.1.4.3[1]/Skins/Blue/Icons$
Run Code Online (Sandbox Code Playgroud)
Aaaah,好多了!我的第一种方法是将upath的UNIX样式路径转换为Windows样式路径并命名新的var 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
Run Code Online (Sandbox Code Playgroud)
一切都很好,除了读取的行:
set upath2=%cd:%unixhome%="~"%
Run Code Online (Sandbox Code Playgroud)
我意识到它弄乱并识别%cd:%和%="〜"%作为变量,并给我一个错误信息.我真的非常抱歉像这样漫无边际:)但是长话短说,有没有办法取变量A的文本,如果在变量B中找到,则替换该文本?
谢谢大家!
打开延迟扩展
setlocal enabledelayedexpansion
Run Code Online (Sandbox Code Playgroud)
并使用
set upath2=!cd:%userprofile%=~!
Run Code Online (Sandbox Code Playgroud)
请注意,这setlocal将启动一个新的变量作用域,并且在该作用域内对环境变量所做的任何更改都不会在其外部保留。
但是,您可以执行以下操作来一次性使用:
setlocal enabledelayedexpansion
set upath2=!cd:%userprofile%=~!
endlocal&set upath2=%upath2%
Run Code Online (Sandbox Code Playgroud)