Shahar Hamuzim Rajuan
Shahar Hamuzim Rajuan

Reputation: 6129

Find the first string in a text file in whatever line I want using batch file

I want to get the first string of the second line of a text file using a batch file, If possible get the first string of any line I want.

This is the text I want to parse:

CONTAINER ID        IMAGE               COMMAND                    CREATED             STATUS                      PORTS               NAMES
94c9dc4ba7c6        clearcmd6           "c:\\windows\\system..."   24 minutes ago      Exited (0) 23 minutes ago                       mycont

So I expect to get 94c9dc4ba7c6 inside a parameter.

Is that possible?

Upvotes: 1

Views: 423

Answers (2)

Compo
Compo

Reputation: 38623

You would need to bear in mind that the first string would be up to the first whitespace.

@Echo Off
Set "file=text-file.txt"
Set "line=34"
Set/A "skip=line-1"
For /F "UseBackQ Skip=%skip%" %%A In ("%file%") Do Set "var=%%A"
Setlocal EnableDelayedExpansion
Echo(!var!
EndLocal
GoTo :EOF

You just input your required file name replacing text-file.txt on line number 2 and line number replacing 34 on line 3.

Upvotes: 0

Sam Denty
Sam Denty

Reputation: 4085

Batch-file:

@echo off
for /f "USEBACKQ tokens=1 skip=1 delims= " %%a in (text-file.txt) do (echo %%a)

text-file.txt

CONTAINER ID        IMAGE               COMMAND                    CREATED             STATUS                      PORTS               NAMES
94c9dc4ba7c6        clearcmd6           "c:\\windows\\system..."   24 minutes ago      Exited (0) 23 minutes ago                       mycont

Output:

94c9dc4ba7c6

Upvotes: 1

Related Questions