[英]How to handle carriage return with windows batch script?
I want to use bat to automate some of my work. 我想使用bat来自动化一些工作。 It should first look up the value of a certain registry key, and then copy some files to the directory that included in the registry key value.
它应该首先查找某个注册表项的值,然后将一些文件复制到注册表项值中包含的目录中。 I used reg query command to look up registry, such as:
我使用reg查询命令来查找注册表,例如:
REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROCESSOR_ARCHITECTURE
The result seems contains carriage return and I need to remove it, I've tried some solutions but all failed. 结果似乎包含回车符,我需要删除它,我尝试了一些解决方案,但都失败了。 Could anyone help me?
有人可以帮我吗?
For that particular case, you can start with: 对于这种特定情况,您可以从以下内容开始:
for /f "tokens=3" %i in ('REG QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROCESSOR_ARCHITECTURE ^| findstr PROCESSOR_ARCHITECTURE') do set x=%i
which will set %x%
to x86 (in my case). 这会将
%x%
设置为x86(在我的情况下)。
If the third value on the line can contain spaces, you'll need to get a bit trickier 如果该行的第三个值可以包含空格,则需要更棘手
The following script shows one way to be trickier. 以下脚本显示了一种更棘手的方法。 It basically uses a debug line to produce fictional output from
reg
that gives you an architecture with spaces. 它基本上使用调试行从
reg
生成虚构的输出,从而为您提供带空格的体系结构。
@setlocal enableextensions enabledelayedexpansion
@echo off
for /f "tokens=2*" %%a in ('echo. PROCESSOR_ARCHITECTURE REG_SZ x86 64-bit grunter') do (
set arch=%%b
)
echo !arch!
endlocal
The output of that is: 输出为:
x86 64-bit grunter
as expected (keep in mind it collapses multiple spaces into one). 如预期的那样(请记住,它会将多个空间折叠为一个)。 The
tokens=2*
bit puts token 2 ( REG_SZ
) into %%a
and all following tokens into %%b
. tokens=2*
位将令牌2( REG_SZ
)放入%%a
并将所有后续令牌放入%%b
。
So a good final script would be: 因此,一个好的最终脚本是:
@setlocal enableextensions enabledelayedexpansion
@echo off
set id=HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
set key=PROCESSOR_ARCHITECTURE
for /f "tokens=2*" %%a in ('REG QUERY "!id!" /v !key! ^| findstr !key!') do (
set arch=%%b
)
echo !arch!
if !arch!==x86 echo arch was x86
endlocal
This script outputs: 该脚本输出:
x86
arch was x86
so you know it's being set as you desire. 所以您知道它正在按您的意愿进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.