4

I am using grep on windows to filter a file and would like to pipe the output to another batch script.

e.g.

grep "foo" bar.txt | mybatch.bat

and in mybatch i would like to process each matching line

e.g. mybatch.bat:

echo Line with foo: %1

on linux I can solve this via

grep "foo" bar.txt | while read x; do mybatch.sh $x; done

but no idea how I can do this on a windows machine.

Thanks in advance!

2 Answers 2

6

You can use for:

for /f %x in ('grep "foo" bar.txt') do call mybatch.cmd "%x"

This will call your batch file once for every non-empty line, just as your shell script example would do.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, works well, I output my pipe chain into a temp file and then do the for loop on the temp file (happens in another batch file): for /f "tokens=*" %%x in ('type temp.tmp') do call test.cmd "%%x" but it adds quotes to each line that is passed to the test.cmd so if test.cmd does echo Line is %1 I will get Line is "foo" (with quouts) while the lines in the temp file are without. any trick to get rid of the quotes?
Use %~1 instead. But there is no need to resort to type in that case, for /f %%x in (temp.tmp) do ... does the same.
this is no pipe... the task may be done but does the question remain actually unanswered? (edit: proposed to rename the question)
0

Here's the trick of the trade:

head.bat

@echo off

setlocal ENABLEDELAYEDEXPANSION
set n=%1

for /F "tokens=*" %%x in ('more') do (
echo %%x
set /A n -= 1
if !n! EQU 0 exit /b
)

Using it:

REM print the first 10 lines:
type test.txt | head 10 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.