【问题标题】:Find a string containing a substring in windows batch file在 Windows 批处理文件中查找包含子字符串的字符串
【发布时间】:2016-02-25 23:11:21
【问题描述】:

我有一个文本文件 (filename.txt),其中包含

ProductABC_Test.txt
ProductDEF_Test.txt
ProductHIG_Test.txt
ProductIJK_Test.txt

我将传递一个变量(例如:product=ABC,它将是 ProductABC_Test.txt 的子字符串)。所以我需要从 filename.txt 中获取正确的测试名称(ProductABC_Test.txt)。

我试过下面的代码-

SETLOCAL ENABLEEXTENSIONS
@echo off
set product=ABC
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (filename.txt) do 
(
    set str=%%A
    if NOT %str% == !%str:product=% 
    (
        set test_suite=%%A
    )
)
ENDLOCAL
echo %test_suite%

但我没有得到正确的结果。

【问题讨论】:

  • 您需要Delayed Variable Expansion,因为您正在设置读取代码块中的变量,所以!str!而不是%str%,还有!str:%product%=!。 ..
  • @aschipfl - 你的观点看起来很棒。现在我了解了延迟变量扩展。非常感谢
  • 请注意DOS是80/90年代的操作系统!请改用标签 Windows。

标签: batch-file dos


【解决方案1】:

您可以使用以下代码查找包含您的子字符串的行:

@echo off
SETLOCAL ENABLEEXTENSIONS
set product=ABC
set test_suite="not found"
SETLOCAL EnableDelayedExpansion
for /F "tokens=*" %%A in (filename.txt) do (
    set str=%%A
    Echo.!str! | findstr /C:"!product!">nul
    if !errorlevel!==0 set test_suite=!str!
)
echo %test_suite%
pause

【讨论】:

  • 非常感谢@Dennis。你给了我所需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 2022-01-10
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多