【问题标题】:batch file find string and give line number off it批处理文件查找字符串并给出行号
【发布时间】:2020-04-17 20:22:37
【问题描述】:

我正在尝试编译批处理文件以在 txt 文件中搜索字符串,当它找到时给出行号并将其放入变量以便我可以在语句中使用它

例子

name.txt

carolina
rita
sara
andre

在上面的示例中,我想找到 %username% = Andre,如果 %username% 不在列表中,我想返回一个变量 4,我希望它归因于名称“Hello” 因为“andre”在第 4 行

我找到了一个代码,但我无法使其正常运行

    @echo off &setlocal
set "search=%username%"
set "replace=kordo anstataui"
set "textfile=name.txt"
set "newfile=new.txt"

(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"

type "%newfile%"

我希望它能帮助代码帮助

ps:文笔不好请见谅

【问题讨论】:

    标签: batch-file


    【解决方案1】:

    您找到了 FINDSTR 命令。嗯,我想知道它会做什么......

    for /f "delims=:" %%N in ('findstr /i /x /n andre "%textfile%"') do set line=%%N
    

    在命令提示符下使用 help findstrfindstr /? 获取帮助。有关标准帮助中未提供的其他信息,请参阅 What are the undocumented features and limitations of the Windows FINDSTR command?

    【讨论】:

    • 你好,经过大量搜索,我找到了我想要的东西,但我无法将其付诸实践 我找到了另一个代码来解决我的问题并且它有效username% 而不是 "installer id:" 如果我​​能做到,我的问题就解决了 @echo off set "file=build_info.txt" set "installer_id=" for /f "tokens=2* delims=: " %%A in ( 'findstr /bc:"Installer ID:" "%file%"' ) do set "installer_id=%%B" echo %installer_id% pause>null
    • @user3121120 然后将“安装程序 ID:”替换为“%username%”。这现在将搜索用户名并将其存储在 INstaller ID 变量中
    • @dbenham:当我从for /f "delims=:" %N in ('findstr /i /x /n andre "%textfile%"') do set line=%Necho !line!时,我得到的回复是!line!而不是数字4。你知道为什么吗?
    • @Zimba - 可能是因为延迟扩展尚未启用。 - setlocal enableDelayedExpansion
    • @dbenham:已启用。这是我所拥有的:for /f "delims=:" %N in ('findstr /i /x /n andre "name.txt"') do set line=%N echo %line% %line% echo !line! !line! 在我粘贴评论中的代码后,它现在可以工作了。当我在记事本中编辑它以删除多余的 % 时,一开始没有用,现在仍然没有用。
    【解决方案2】:

    此代码给出包含 andre 的所有行,并将包含匹配项的最后一行存储在变量中:

    for /f "tokens=1* delims=][" %i in ('find /n "andre" ^< name.txt') do echo Hello %j, you are in line %i & set line=%i
    

    【讨论】:

      【解决方案3】:

      我使用这个非常简单。

      FOR /F "delims=: tokens=1*" %i in ('findstr /N /I "String2Find" "file2read.log"') do ( set VARIABLE=%i )
      echo %VARIABLE%
      

      【讨论】:

      • 但这并没有解决问题,如何将行号存储在变量中
      • 抱歉,这会将其作为变量返回。如果您有多次点击。你会得到最后一个。
      • 但现在它是 dbenham 的答案的副本
      • 我会称之为那个的变体,但是是的,它应该是对那个的评论而不是回答。
      猜你喜欢
      • 2021-02-24
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2014-09-30
      相关资源
      最近更新 更多