Sending result from FIND to IF in cmd

2019-08-16 01:56发布

after receiving critics for not asking the question the right way, I have returned again with what I think is better way. I am trying to solve homework problem in which I have to write a batch file and I am stuck.

When this batch file is called in CMD it receives 4 parameters:

  • (1) Path to some directory with \ at the end; example: C:\Users\PC\Desktop\
  • (2) Extension of the file; example: txt
  • (3) Some string; example: "ab"
  • (4) An integer; example: 3

The purpose of this batch file is to find all files X with extension (2) on local directory and all subdirectories received by (1), which have more than (4) lines in them that have substring (3) and write in console next sentence:

"File X has more than (4) liens, more precise Y, which have substring (3)". Where X is full path of the file that fulfills those conditions and Y exact number of lines in which substring is found.

Input in console should be like this: myfile.bat C:\Users\PC\Desktop\ txt ab 3

My attempt of solving this was like this:

@echo off
for %%a in ('dir /s %1*.%2') do (
    for /f "delims= " %%G in ('find /c "%3" ^<%%a') do (
        set linecount=%%G
        if %linecount% gtr %4 (
            echo File %%a has more than %4 lines, more precisley %linecount% which have substring %3
        )
    )
)

Hope this time I've done it partially right.

2条回答
时光不老,我们不散
2楼-- · 2019-08-16 02:23

I found solution:

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /s /b "%1*.%2"') do (
    for /f "delims=: tokens=3" %%g in ('find /c "%3" "%%a"') do (
        set linecount=%%g
        if !linecount! gtr %4 (
            echo File %%a has more than %4 lines, more precisley !linecount! which have substring %3
        )
    )
)

Big thanks to all for making this possible.

查看更多
相关推荐>>
3楼-- · 2019-08-16 02:39

Based on your question parameters to date, and just for the hell of it, here's a one line batch file solution, (with very limited testing):

@For /F "Delims=" %%A In ('Dir/B/S/A-D-S-L "%~1*.%2"') Do @For /F "Tokens=3Delims=:" %%B In ('Find /I /C "%~3" "%%A"') Do @If %%B Gtr %4 Echo File %%A has more than %4 lines, more precisley%%B, which have substring %3

This one uses the Where command, (which I prefer because it will not work with trailing backslashes tagged to directory names):

@For /F "Delims=" %%A In ('Where/R "%~1" *.%2') Do @For /F "Tokens=3Delims=:" %%B In ('Find /I /C "%~3" "%%A"') Do @If %%B Gtr %4 Echo File %%A has more than %4 lines, more precisley%%B, which have substring %3
查看更多
登录 后发表回答