Suman Nagaraj
Suman Nagaraj

Reputation: 145

Batch script to find a value in the first column of text file based on the parameters

I have a file links.txt:

1 a b c
21 b d
14 c j k l
5 d r e

test.bat 1:

@echo off
for /f "tokens=*" %%c in ('findstr /b "%*" links.txt') do (
echo %%c
)

I passed "1" as parameter to test.bat and expected output is "1 a b c". But it is displaying all the rows which is beginning with "1".

Upvotes: 0

Views: 1739

Answers (1)

Magoo
Magoo

Reputation: 80033

Your command is "find all of the lines in the file that /b (begin) 1 (passed in as a parameter).

You need

for /f "tokens=*" %%c in ('findstr /b /c:"%1 " links.txt') do (

as the syntax of findstr requires /c:"find this string" /c:"or this string" to find an exact string containing spaces - "find this string" will find find or this or string

You could process your input-parameter string like:

SET "params= %*"
SET "params=%params: = " /c:"% ""
SET "params=%params:~2%"
findstr /b %params% ....

OR perhaps use

findstr /b /g:"afilename" ...

where afilename contains your required strings one to a line with the spaces appended as required. Note that many editors will drop trailing spaces by default.


For the example case in the comment...

@echo off
setlocal
SET "params= %*"
SET "params=%params: = " /c:"% ""
SET "params=%params:~2%"
echo the params string is %params%
for /f "tokens=*" %%c in ('findstr /b /L %params% links.txt') do (
echo %%c
)

params is assigned the value of the command-tail. Each space is then replaced by " /c:" and " appended to the end. Then only those characters after the second are used.

Upvotes: 1

Related Questions