[英]How to find lines in a text file containing specific strings and replace each whole line with a new string,?
[英]How to store the line numbers of the lines containing a specific string in a text file in an environment variable?
我目前有這個批處理代碼,它告訴我這個字符串出現在文本文件中的次數。
@ECHO OFF
set /a Numb=0
for /f %%i in ('FINDSTR /N .* %1') do (set /a Numb+=1)
echo %Numb%
我需要另一段代碼,將文本所在的行號輸出到變量。
如何將包含特定字符串的行的行號存儲在環境變量的文本文件中?
我的這個任務的批處理代碼需要指定文件名和搜索字符串作為運行批處理文件的參數,並進行一些錯誤檢查:
@echo off
setlocal EnableDelayedExpansion
set "FileName=%~1"
set "Search=%~2"
rem Exit batch file if the two required arguments were not specified.
if "%FileName%" == "" (
echo Error: There is no file name specified as first parameter.
goto ErrorOuput
)
if "%Search%" == "" (
echo Error: There is no search string specified as second parameter.
goto ErrorOuput
)
if not exist "%FileName%" (
echo Error: The file "!FileName!" does not exist.
goto ErrorOuput
)
set "LineNumbers="
for /F "delims=:" %%I in ('%SystemRoot%\System32\findstr.exe /I /L /N /C:"%Search%" "%FileName%" 2^>nul') do set "LineNumbers=!LineNumbers!,%%I"
if "%LineNumbers%" == "" (
echo Info: The string "!Search!" could not be found in "!FileName!"
goto EndBatch
)
rem Remove the comma from begin of list of line numbers.
set "LineNumbers=!LineNumbers:~1!"
echo Found "!Search!" in "!FileName!" on the lines:
echo.
echo %LineNumbers%
goto EndBatch
:ErrorOuput
echo.
echo Usage: %~nx0 "file name" "search string"
:EndBatch
echo.
endlocal
pause
錯誤檢查未完成。 仍然可能發生錯誤。 例如,第一個參數可能是*.txt
會產生錯誤的結果,因為FINDSTR輸出在這種情況下首先是文件名,然后是冒號,接下來是行號,還有一個冒號而不是只是行號和冒號,就像搜索時一樣在一個文件上。
例如,在命令提示符窗口中至少運行一次
findstr /I /L /N /C:"endbatch" "SearchString.bat"
將上面的批處理代碼存儲在當前目錄中的SearchString.bat
文件中,以查看此處的FOR進程命令。
要了解使用的命令及其工作方式,請打開命令提示符窗口,執行以下命令,並完全閱讀為每個命令顯示的所有幫助頁面。
call /?
...解釋%~1
和%~2
echo /?
endlocal /?
findstr /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
另請閱讀有關使用命令重定向運算符的Microsoft文章,以解釋2>nul
以重定向FINDSTR輸出的錯誤消息, 以便將STDERR處理到設備NUL,以便在搜索文件中找不到搜索到的字符串時將其抑制。 必須使用^
來轉義重定向運算符>
,以便在執行FINDSTR時應用重定向,而不是將2>nul
解釋為命令行中的無效位置的命令FOR的重定向。
使用以下批處理文件。
TEST.CMD:
@echo off
setlocal enabledelayedexpansion
set line_numbers=
for /f "skip=2 delims=[]" %%i in ('find /n /i "%1" names.txt') do (
set line_numbers=!line_numbers! %%i
)
rem skip leading space
echo %line_numbers:~1%
endlocal
筆記:
test.cmd
。 names.txt
(您也可以將其作為參數傳遞)。 line_numbers
。 用法示例:
F:\test>type names.txt
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
Joe Bloggs, 123 Main St, Dunoon
Arnold Jones, 127 Scotland Street, Edinburgh
F:\test>test bloggs
1 3 5
F:\test>test jones
2 4 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.