Home > Enterprise >  Get a string in a line with a string pattern (CMD) - Windows Batch
Get a string in a line with a string pattern (CMD) - Windows Batch

Time:03-11



I'm using windows command prompt (cmd).
I have this file "myfile.txt" and i want to get the string in each line that match my pattern.

For instance, if i have this in "myfile.txt":

The file alpha_123.txt has been created
The file gama_234.txt has been created
The new file alpha_789.txt has been created

And if I search for "alpha", the result should be this:
alpha_123.txt
alpha_789.txt

For now i have this code: findstr /c "alpha" myfile.txt but it returns the full line, but i just want the specific string.

Thanks in advance!

CodePudding user response:

This can be used at a cmd command-prompt on windows.

powershell -nop -c ((sls 'alpha.*?\s' myfile.txt).Matches.Value).Trim()

If placed into a cmd batch-file, aliases should not be used.

powershell -NoLogo -NoProfile -Command ^
    ((Select-String -Pattern 'alpha.*?\s' -Path 'myfile.txt').Matches.Value).Trim()

CodePudding user response:

Assuming you're in the correct directory, something like this should work.

for /f "tokens=3 delims= " %G in ('findstr "alpha" MyFile.txt') do @echo %G

Or something like this:

for /f "tokens=3 delims= " %G in ('findstr /r "\<alpha_.*txt" MyFile.txt') do @echo %G

CodePudding user response:

Quite straight forward: get each line, write each word (token) and filter for the desired string:

@echo off
setlocal 
set "search=alpha"

for /f "delims=" %%a in (t.txt) do (
  for %%b in (%%a) do (
    echo %%b|find "%search%"
  )
)
  • Related