简体   繁体   中英

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



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!

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

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()

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%"
  )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM