Home > database >  Get a string in a line with a string pattern (CMD)
Get a string in a line with a string pattern (CMD)

Time:03-09



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 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:

Assuming you're in the correct path, something like this should work. Include or skip echo off and echo on as you see fit.

echo off
for /f "tokens=3 delims= " %G IN ('findstr "alpha" MyFile.txt') DO echo %G
echo on

Or, perhaps something along the lines of this

echo off
for /f "tokens=3 delims= " %G IN ('findstr /r "\alpha_.*txt" MyFile.txt') DO echo %G
echo on

CodePudding user response:

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

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

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
  • Related