比较for(if语句)中的批处理中的字符串 [英] Comparing Strings in Batch inside a for (if statement))

查看:38
本文介绍了比较for(if语句)中的批处理中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些文件名的file1.txt.我想从文件中读取文件,如果文件名包含"xyz"字符串,则需要运行一些命令,如果没有,则需要运行其他命令无法执行此操作,需要您的帮助,尝试了很多方法,但无法弄清楚这是我尝试的示例代码:

I have a file1.txt with some file names. I want to read from the file and if the file name contains "xyz" string i need to run some commands and if not some other commands Not able to do this and need your help,tried a lot of methods but not able to figure out Here's the sample code i tried:

 @echo off
 setlocal EnableDelayedExpansion

 for /F "tokens=1,2,3 delims=" %%i in (file1.txt) do (
     set f=%%i
     set z=XYZ
     echo !f! >>test.txt
     if /i "!f!" == "!z!" (
         echo matched >> test.txt
     ) else ( 
         echo nomatch >> test.txt
     )
 )

推荐答案

要比较一个字符串是否包含另一个字符串,您可以像这样进行操作(请注意,这是不区分大小写的,因为基础

To compare whether a string contains another one, you can do it like this (note that this is case-insensitive, because the underlying sub-string expansion syntax is case-insensitive on its own):

if "!STRING!"=="!STRING:%SUB%=!" echo Sub-string "%SUB%" NOT found within "!STRING!"

在您的脚本中实现了以上方法:

Here the above approach is implemented into your script:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_INFILE=file1.txt"
set "_OUTFILE=test.txt"
set "_SUBSTR=XYZ"

>> "%_OUTFILE%" (
    for /F "usebackq tokens=1-3 delims=" %%L in ("%_INFILE%") do (
        set "LINE=%%L"
        setlocal EnableDelayedExpansion
        echo(!LINE!
        if not "!LINE!"=="!LINE:%_SUBSTR%=!" (
            echo matched
        ) else ( 
            echo nomatch
        )
        endlocal
    )
)

endlocal
exit /B

此外,我还改进了以下内容:

In addition, I improved the following things:

  • constant-like variables are predefined at the beginning;
  • the returned text is redirected once only; replace >> by > to overwrite an already existing file rather than appending to it;
  • delayed expansion is toggled within the loop in order not to lose exclamation marks in the text; note that the string in _SUBSTR must not contain such;
  • all file paths used in the script are enclosed within quotation marks;
  • the quoted set syntax is used throughout the script;
  • code indention is used for improved readability;

或者,您可以使用 find 命令,仅返回 file1.txt 中包含%SUB%中子字符串的行;添加/I 选项以执行不区分大小写的搜索:

Alternatively, you could use the find command, which returns only those lines within file1.txt that contain the sub-string in %SUB%; add the /I option to do a case-insensitive search:

find "%SUB%" "file1.txt"

这篇关于比较for(if语句)中的批处理中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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