简体   繁体   中英

Count number of |

I need help with a script, the script is supposed to count the number of | before a specific string.

info.txt

text=jam|hello=123|result=ok|cow=cat|...

So in this example the answer should be 2 if you search for result= Is this possible in batch?

try this:

@ECHO OFF &SETLOCAL
SET "string=text=jam|hello=123|result=ok|cow=cat|..."
SET "stop=result=ok"
SET "char=|"

SET /a count=-1
SET "org=%string%"
:loop
FOR /f "tokens=1*delims=%char%" %%a IN ("%string%") DO SET "this=%%a"&SET "that=%%b"
IF DEFINED that (SET "string=%that%") ELSE (SET "string=%this%")
SET /a count+=1
IF NOT DEFINED string (ECHO NOT found: "%stop%" &GOTO :EOF)
IF NOT "%this%"=="%stop%" GOTO :loop
ECHO Number of "%char%" IN "%org%" until "%stop%": %count%

This uses a helper batch file called repl.bat: from - http://www.dostips.com/forum/viewtopic.php?f=3&t=3855

If you call this code below searchstring.bat then you can launch it like this

searchstring "result="

It expects only one match per file and is case sensitive.

@echo off
type "file.txt" | find "%~1" | repl "(.*).%~1.*" "$1" | repl "\x7c" "\r\n" x | find /c /v ""

This batch file below will return a count of line number and the number itself, when the number is greater than zero, per each line in the file.txt

@echo off
if "%~1"=="" ( echo add a search term&pause&goto :EOF)
for /f "tokens=1,* delims=:" %%a in ('findstr /n "^" "file.txt" ') do (
for /f %%c in (' echo "%%b"^| find "%~1" ^| repl "(.*).%~1.*" "$1" ^| repl "\|" "\r\n" x ^| find /c /v "" ') do (
if %%c GTR 0 echo Line %%a: %%c
)
)
pause

If you want, eg, 3rd string:

SET "text=jam|hello=123|result=ok|cow=cat|..."
FOR /F "TOKENS=3" %%t IN ("%text%") DO ECHO %%t

If you want, eg, 3rd string and following:

SET "text=jam|hello=123|result=ok|cow=cat|..."
FOR /F "TOKENS=2,*" %%t IN ("%text%") DO ECHO %%u

Here's another way (uses your info.txt file). Case insensitive. Handles multiple lines with matching string in file.

@echo off
set "SpecificString=result=ok"
set /A cnt=0
for /F "tokens=*" %%A IN (info.txt) do (
   for /F "usebackq tokens=*" %%B IN (`echo."%%A" ^| find /I "%SpecificString%"`) do (
      call :Parse "%%~A"
      )
   )
pause
goto :eof

:Parse
for /F "usebackq tokens=1* delims=^|" %%B IN (`echo."%~1"`) do (
   if /I "%%~B"=="%SpecificString%" (
      echo.Cnt=%Cnt% in "%%A"
      echo.
      set /A Cnt=0
      goto :eof
      )
   set /A Cnt+=1
   call :Parse "%%~C
   )
goto :eof

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM