迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 操作系统 >

批处理文件中的字符串比较

作者:迹忆客 最近更新:2023/05/18 浏览次数:

字符串是字符的有序集合。

可以使用批处理文件中的条件命令比较字符串,即 if、if-else 和 for 命令。 字符串可能包含空格和特殊字符,这会在正常执行时导致批处理文件出错。

此外,如果字符串包含双引号,则可能会导致错误。

本教程将介绍使用 if、if-else 和 for 命令比较批处理文件中字符串的不同方法。


在批处理文件中使用 if 和 if-else 命令进行字符串比较

if 命令在设定值和预期值之间执行条件运算和逻辑比较。 它可以检查文件是否存在、比较字符串,甚至检查错误。

使用 if 命令进行字符串比较

让我们举个例子来检查字符串是否相等。 如果它们相等,它将使用 echo 命令显示输出。

@echo off
SetLocal

set string1="Hello World"
set string2="Hello World"

if %string1% == %string2% (echo "Both the strings are equal")
cmd /k

testfile if command

输出:

output if command

使用 if-else 命令进行字符串比较

@echo off
SetLocal

set string1="Hello World"
set string2="HELLO WORLD"
set string3="Hello World"


if %string1% == %string2% (echo string 1 and string 2 are equal echo the string is %string2%) else if %string1% == %string3% (echo string1 and string 3 are equal
echo the string is %string3%) else (echo all strings are different)
cmd /k

testfile if else

输出:

output if else command

注意:

  1. 不要在括号之间留空格。
  2. 当字符串或变量包含空格或特殊字符时,将它们放在双引号中。

使用 if 命令,您可以使用 /I 进行不区分大小写的字符串比较,如果条件为假,则不运行该命令。

您还可以使用比较运算符,例如 EQU(等于)、NEQ(不等于)、LSS(小于)、LEQ(小于或等于)、GTR(大于或等于)、GEQ(大于或等于 ) 用于比较值。 但是,这些运算符不能用于比较字符串。

使用 if-else 命令比较包含双引号的字符串

如果字符串或变量包含双引号,请使用 SetLocal 命令启用延迟扩展。 使用 ! 代替 ”。

相同的代码如下例所示:

@echo off
SetLocal EnableDelayedExpansion

set string1="Hello "World""
set string2=""HELLO WORLD""
set string3="Hello World"

if !string1! == !string2! (echo "string 1 and string 2 are equal") else if !string1! == !string3! (echo "string1 and string 3 are equal") else (echo "All strings are different")
cmd /k

testfile if else string with double quotes

输出:

output if else strings with double quotes


在批处理文件中使用 for 循环进行字符串比较

for 命令用于为一组文件中的每个文件运行指定的命令。

显示了批处理文件中 for 命令的语法。

for {%%|%}<variable> in (<set>) do <command> [<commandlineoptions>]

让我们举一个例子,我们必须比较字符串以显示 Windows 操作系统版本:

@echo off
SetLocal EnableDelayedExpansion
for /f "usebackq tokens=1 delims=" %%I in ("C:\Users\Aastha Gas Harda\Desktop\testfile1.txt") do (
set string=%%I
echo %%I
if "%%~I" == "HelloWorld" (echo "match found") else (echo "match not found")
)
PAUSE

testfile for loop

输出:

output for loop

在上面的示例中,使用了一个 for 循环来比较字符串值。 如果字符串值等于 HelloWorld,它会将输出显示为找到匹配项。

delims 指定分隔符集,tokens 指定每行中的哪些标记将传递给 for 循环。 每当我们在 for 循环中使用引号时,都必须使用 usebackq。

因此,我们已经讨论了在批处理文件中比较字符串的不同方法。 除了比较字符串外,这些条件命令还可用于从文本文件或日志文件中查找指定的值或文本。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便