-1



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!

reiver
  • 117
  • 1
  • 8
  • You'll probably have to write a small program. [You could try AWK](https://en.wikipedia.org/wiki/AWK) which is a relatively easy to learn text/data extraction and manipulation program. – JJF Mar 09 '22 at 12:21
  • AWK is linux based right? I'm working with windows batch – reiver Mar 10 '22 at 15:14

3 Answers3

0

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
Mofi
  • 46,139
  • 17
  • 80
  • 143
notjustme
  • 2,376
  • 2
  • 20
  • 27
0

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()
lit
  • 14,456
  • 10
  • 65
  • 119
0

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%"
  )
)
Stephan
  • 53,940
  • 10
  • 58
  • 91