Kalaschnik
Kalaschnik

Reputation: 898

Get the end of a string using findstr command

As there is no native grep on Windows, I'm struggling to get the end of the substring located at the end of a line, which is prepended by some spaces.

My search string always has the following pattern:

Some description about something: the-value-I-want-separated-by-hyphens

(there are 5 spaces separating the description and the value)

With Regex I could do: [^ ]+$ which returns: the-value-I-want-separated-by-hyphens (see here: https://regex101.com/r/zgTGWA/1)

Yet this does not work in my cmd.

Context

I got a bunch of files, that look like this:

file.txt

Description Key1:     the-value-I-want-separated-by-hyphens
Another Description Key2:     another-value
Another Description Key3:     another-value

my testing code in the cmd: type file.txt | findstr "Key1" | findstr /R /C"[^ ]+$"

Although the first find string works great for filtering the desired line, the second one does not return the desired value.

Thanks for any advice

Upvotes: 1

Views: 1185

Answers (1)

Squashman
Squashman

Reputation: 14290

You can use wildcard substring replacement to remove the lead portion of the line. The wild card replacement is non greedy so it will only remove the section to where it finds the first set of 5 spaces. I used the colon to tighten up the matching as well.

@echo off

FOR /F "delims=" %%G IN ('type file.txt ^| findstr "Key1:"') DO (
    set "line=%%G"
    setlocal enabledelayedexpansion
    echo !line:*:     =!
    FOR /F "delims=" %%H IN ("!line:*:     =!") DO endlocal&set "result=%%H"
)
echo Result=%result%
pause

And based on your input file this is the result.

C:\BatchFiles\substring>so.bat
the-value-I-want-separated-by-hyphens
Result=the-value-I-want-separated-by-hyphens
Press any key to continue . . .

Upvotes: 2

Related Questions