[英]Batch to find a string of number&letter combination only in first 10 characters (in a txt file) per row and print the whole row
[英]Batch - find a string in first 10 characters on line and print whole line
我在使用findstr命令時遇到麻煩。 我正在使用批處理文件來執行一個過程,該過程將搜索文件夾中的所有.txt文件並打印出前面定義的前10個字符為字符串的行。 到目前為止,我一直在使用此批處理:
for /f "delims=" %%I in ('dir/B *.txt') do ( for /f "delims=" %%J in (%%I) do ( set "=%%J" call echo %%:~0,10%%|findstr "R0621 32411"&&call echo %%_%% >> search.txt ) ) endlocal但是,這一批不以某種方式不會打印出包含R0621或32411之類的字符串的行。這是一個錯誤嗎? 當我嘗試典型的findstr批處理時,它可以正常工作並打印出行。 例如:
\n findstr“ R0621 32411” * .txt >> search.txt\n該批次搜索的.txt文件如下所示:
\n AA32411 AAA RANDOMTEXTANDNUMBERS 13121313212153\n BBR0621 BBB RANDOMTEXTANDNUMBERS 78975487798797\n CCY4488 CCC隨機文字和數字44455577799998\n我不能使用findstr,因為它會在10個字符之后查找字符串,而我不需要這些行(我只需要那些具有在每行的前10個字符中定義的字符串的字符串)。
有沒有其他選擇? 我試圖搜索互聯網,但在任何地方都找不到任何幫助。 另外,為了更好地理解,您可以檢查我以前的線程“ 批處理”以找到每行僅前10個字符(在txt文件中)的數字和字母組合字符串,並打印整行
@echo off
setlocal EnableDelayedExpansion
rem Seek the target strings in all .txt files
(for /F "tokens=1* delims=:" %%a in ('findstr "R0621 32411" *.txt') do (
rem Check that the target string(s) exists in first 10 characters of found lines
set "line=%%b"
rem Get just the first 10 characters
set "tenChars=!line:~0,10!"
rem If R0621 was in first 10 characters
if "!tenChars:R0621=!" neq "!tenChars!" (
echo !line!
rem If 32411 was in first 10 characters
) else if "!tenChars:32411=!" neq "!tenChars!" (
echo !line!
)
)) > search.out
請注意,如果輸出文件也擴展名為.txt這將被包含在原FINDSTR! 您可以在最后使用ren search.out search.txt
命令重命名具有正確擴展名的輸出文件,或在其他目錄中創建具有.txt擴展名的輸出文件。
@echo off
setlocal enableextensions
set "tempFile=%temp%\%~nx0.tmp"
set "outputFile=search.out"
(for %%a in (
R0621 .R0621 ..R0621 ...R0621 ....R0621 .....R0621
32411 .32411 ..32411 ...32411 ....32411 .....32411
) do @echo %%a) > "%tempFile%"
type nul > "%outputFile%"
for %%a in (*.txt) do findstr /r /b /g:"%tempFile%" "%%~a" >> "%outputFile%"
del /q "%tempFile%" >nul 2>nul
endlocal
它只是使用要搜索的正則表達式構造一個臨時文件。 由於字符串應該位於前10個字符中,並且它們的長度為5個字符(所有這些都是硬編碼的,但是可以改編),因此搜索字符串可以從第1、2,...到第6行開始開始(正則表達式中的點表示任何字符都可以在該位置)
構建完搜索文件后, for
循環將遍歷.txt
文件,對於每個文件,我們都使用findstr
搜索,在行( /b
)的開頭搜索從中讀取的正則表達式( /r
)生成的文件( /g:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.