在CMD中转义输出 [英] Escaping outputs in CMD

查看:125
本文介绍了在CMD中转义输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我运行返回&的内容,或其他具有特殊含义的字符,而我尝试在脚本中使用它,我将如何对其进行转义?

If I run something that returns with a & or some other character that has special meaning, and I try to use it in a script, how would I escape it?

一个例子是,如果我与同一台计算机上的某人共享一个本地帐户,并且我的用户名显示为John&马特将批处理文件放在具有以下内容的Desktop目录中:

An example would be if I shared a local account with someone in the same computer, and I had a username that says John & Matt. Putting a batch file in the Desktop directory that had something like this:

@ECHO OFF
echo %~dp0

它将返回如下内容:

C:\Users\John
The system cannot find the path specified.

从那时起,如果我继续尝试的话,整个脚本就会中断. 如果有人知道使整个路径出现的方法,我将不胜感激.

And the whole script from that point on breaks if I try to keep going. If anyone knows a way to make the whole path appear, I'd appreciate it.

我没有足够早地澄清这一点.对于那个很抱歉.并不是很擅长解释,但是如果我尝试在变量中使用%〜dp0,并在其上堆叠更多内容,例如

I didn't clarify this enough earlier. Sorry about that. Not really good at explaining, but if I try to use %~dp0 in a variable, and stack more things on top of that, something like

SETLOCAL
set loc=%~dp0
rename "%~dp0Dir\Dir1\Dir2\File.txt" "Something.txt"

如果我在声明变量来解决该问题时放另一组引号,可能会导致重命名命令感到困惑.

It would probably confuse the rename command if I put another set of quotation marks when I'm declaring a variable to fix that issue.

我试图创建的批处理文件基本上删除了该批处理文件所在的文件,将其替换为位于该批处理文件所在目录内的子文件夹中的另一个文件,并将其重命名为其他名称.

The batch file that I was trying to create basically deletes a file where the batch file is located, replaces it with another file in a subfolder located inside the directory where the batch file is, and renames it to something else.

推荐答案

如果要可靠地回显该值而不用引号引起来,则可以使用以下两种策略之一:

If you want to reliably ECHO the value without enclosing quotes, then you can use either of the following strategies:

@echo off
:: Use a FOR loop
for %%F in ("%~dp0") do echo %%~F

:: Use delayed expansion.
:: Note that delayed expansion must be enabled after assignment of fullPath,
:: else any ! within path will be corrupted during the assignment.
set "fullPath=%~dp0"
setlocal enableDelayedExpansion
echo !fullPath!

这篇关于在CMD中转义输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆