Check every string in textfile for substring

256 Views Asked by At

I've searched a long time and didn't find something useful for my problem. It may sound simple, I would be very happy if somebody could help me:

I want to write a batch script, which proves every string in a textfile whether it contains a specific substring. If this is the case, the whole string, which contains this substring, should be printed out. The strings, I'm looking for, are surrounded by double quotes.

My code just works for all lines of my textfile, but I need it for all strings.

Thx in advance!

@echo off
setlocal enableextensions enabledelayedexpansion
    for /f "delims=" %%A in ('findstr "somesubstring" "textfile.txt"') do (
        echo %%A 
    )
2

There are 2 best solutions below

2
On

Perhaps is this what you want?

@echo off
setlocal enabledelayedexpansion

set "substring=somesubstring"
for /f "delims=" %%A in ('findstr "%substring%" "textfile.txt"') do (
   for %%B in (%%A) do (
      set "string=%%~B"
      if "!string:%substring%=!" neq "!string!" echo %%B
   )
)

This Bath file may fail if the characters outside the "strings" (not enclosed in quotes) are special Batch characters.

0
On

I would first use a tool to isolate each string on a single line. Then you can use FINDSTR to return only quoted lines that contain the substring

The trickiest part is isolating the quoted strings. My REPL.BAT regex search and replace utility is a good option. It is a hybrid JScript/batch script that will run natively on any modern Windows machine from XP onward.

type "textfile.txt" | repl (\q.*?\q) \r\n$1\r\n x | findstr /x ^"\".*substring.*\"^"

If you want to see your strings without enclosing quotes, then:

for /f delims^=^ eol^= %%A in (
  'type "textfile.txt" ^| repl (\q.*?\q) \r\n$1\r\n x ^| findstr /x ^"\".*substring.*\"^"'
) do echo %%~A