views:

740

answers:

1

I would like to do some simple parsing within a batch file.

Given the input line:

Foo: Lorem Ipsum 'The quick brown fox' Bar

I want to extract the quoted part (without quotes):

The quick brown fox

Using only the standard command-line tools available on Windows XP.

(I had a look at find and findstr but they don't seem quite flexible enough to return only part of a line.)

+3  A: 

Something like this will work, but only if you have one quoted string per line of input:

@echo OFF
SETLOCAL enableextensions enabledelayedexpansion

set TEXT=Foo: Lorem Ipsum 'The quick brown fox' Bar
@echo %TEXT%

for /f "tokens=2 delims=^'" %%A in ("abc%TEXT%xyz") do (
    set SUBSTR=%%A
)

@echo %SUBSTR%

Output, quoted string in the middle:

Foo: Lorem Ipsum 'The quick brown fox' Bar
The quick brown fox

Output, quoted string in the front:

'The quick brown fox' Bar
The quick brown fox

Output, quoted string at the end:

Foo: Lorem Ipsum 'The quick brown fox'
The quick brown fox

Output, entire string quoted:

'The quick brown fox'
The quick brown fox
Patrick Cuff
You can also use tokens=2 and just use %%A. This method might fail, though, if the quoted string is exactly at the start of the line (I doubt for returns empty matches from tokenizing). The only other option would be to iterate over the string character-wise and keep track of quotes; IOW building an actual parser.
Joey
Good point Johannes. I edited my answer to use your idea and to prepend/append text to the parsed string so that the second token will always be the quoted string.
Patrick Cuff