6

I'm trying to write a simple batch that will loop through every line in a file and if the line contains "apples" or "tomato" then to output that line.

I have this code to find one string and output it but I can't get the second in the same batch. I also want it to echo the lines at it finds them.

@echo OFF

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

It would need to find lines that contain either "apples" or "tomato" I can easily run the code above with the two lines I need but I need the lines to be outputted inter each other.

For example I need:

apple
tomato
tomato
apple
tomato
apple
apple

NOT:

apple
apple
apple

THEN

tomato
tomato
tomato

Thanks in advance.

Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Jsn0605
  • 203
  • 3
  • 5
  • 13

2 Answers2

7

Findstr already does this for you :

@findstr /i "tomato apple" *.txt

Replace *.txt with your wildcard (and tomato apple with the words you want).

If you must change the output, then for comes in handy :

@echo off

for /f %%i in ('findstr /i "tomato apple" *.txt') do @echo I just found a %%i
ixe013
  • 9,559
  • 3
  • 46
  • 77
  • Thanks!! I didn't know it was that simple, I must have been trying too hard. How can I set the line it finds to a variable so I can manipulate it before I output it? – Jsn0605 Oct 11 '12 at 16:13
  • Wow, lol >.< - please disregard my answer - I misunderstood the question. I didn't know it was that easy either. Thanks @ixe013 :) – kikuchiyo Oct 11 '12 at 16:15
  • 1
    See updated answer. It is very basic, you will find many example of manipulation on StackOverflow. If not, ask another question. – ixe013 Oct 11 '12 at 16:22
1

I think I understand the problem: Given some line in diflog.txt with content Sumbitting Receipt, you want to extract all such lines if they also contain apple or tomato. In addition, you want to output the apple lines together, followed by the toomato lines.

This is the best I can do without an actual windows computer to test on and you can fine tune it from here, but this may help:

@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!
)
kikuchiyo
  • 3,391
  • 3
  • 23
  • 29