1

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 
    )
bianconero
  • 215
  • 1
  • 12
  • sounds like a simple `grep` command - check http://www.wingrep.com/ – NirMH Jun 02 '14 at 10:41
  • Can a string span multiple lines? – dbenham Jun 02 '14 at 10:53
  • @dbenham: no, the string just part of one line – bianconero Jun 02 '14 at 11:54
  • NirMH : thx, this looks useful, but i need to generate such a list of strings automatically by batch scripts. – bianconero Jun 02 '14 at 12:19
  • Please indicate what you understand by "string". Are "strings" enclosed in double quotes in the line? What about the characters that are outside the "strings"? Post an example of the file and the desired result. Edit your question please, do NOT post additional information here as a comment. – Aacini Jun 02 '14 at 14:49

2 Answers2

2

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.

Aacini
  • 65,180
  • 12
  • 72
  • 108
  • tried your code, but it doen't provide me just the string, I want- I still get the whole line. But I think I've to handle that in another way- but thx for your answer! – bianconero Jun 03 '14 at 07:27
  • @bianconero - There is a simple bug - it should read `echo %%B` at the end, and then you should get your result. – dbenham Jun 03 '14 at 11:15
1

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
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390