簡體   English   中英

Windows批處理:搜索文件中的所有文件,如果行包含“ apple”或“ tomato”,則將其回顯

[英]Windows Batch: Search all files in file, if line contains “apple” or “tomato” echo it

我正在嘗試編寫一個簡單的批處理,該批處理將遍歷文件中的每一行,如果該行包含“ apples”或“ tomato”,則輸出該行。

我有這段代碼來找到一個字符串並將其輸出,但是我無法在同一批次中獲得第二個字符串。 我也希望它在找到它們時回顯這些線條。

@echo OFF

for /f "delims=" %%J in ('findstr /ilc:"apple" "test.txt"') do (
echo %%J
)

它需要找到包含“ apples”或“ tomato”的行,我可以輕松地用我需要的兩行運行上面的代碼,但是我需要將這些行相互輸出。

例如,我需要:

apple
tomato
tomato
apple
tomato
apple
apple

不:

apple
apple
apple

然后

tomato
tomato
tomato

提前致謝。

Findstr已經為您做到了:

@findstr /i "tomato apple" *.txt

*.txt替換為通配符(將番茄蘋果替換為所需的單詞)。

如果必須更改輸出,則for會派上用場:

@echo off

for /f %%i in ('findstr /i "tomato apple" *.txt') do @echo I just found a %%i

我想我理解問題所在:在diflog.txt中有一行內容為收據收據的行,如果所有這些行還包含蘋果或西紅柿,則要提取所有這些行。 另外,您希望一起輸出蘋果行,然后是番茄行。

如果沒有實際的Windows計算機可以測試,這是我能做的最好的事情,您可以從此處進行微調,但這可能會有所幫助:

@echo OFF
setlocal enabledelayedexpansion

set apples=
set tomatos=

for /f "delims=" %%l in ('findstr /ilc:"Submitting Receipt" "diflog.txt"') do (

  set line=%%l

  for /f "eol=; tokens=1 delims=" %%s in ('echo !line! ^| findstr /ic:"apple"') do (
    set new_apple=%%s
    set apples=!apples!,!new_apple!
  )

  for /f "eol=; tokens=1 delims=" %%s in ('echo !line! ^| findstr /ic:"tomato"') do (
    set new_tomato=%%s
    set tomatos=!tomatos!,!new_tomato!
  )
)

echo Apples:

for /f "eol=; tokens=1 delims=," %%a in ('echo !apples!') do (
  set line_with_apple=@@a
  echo !line_with_apple!
)

echo Tomatos:

for /f "eol=; tokens=1 delims=," %%t in ('echo !tomatos!') do (
  set line_with_tomato=@@a
  echo !line_with_tomato!
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM