Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 351
  • Last Modified:

Search for a string in file and get the next value in it

Example text file contains the below values. I need a batch file to get the value 'sm10' when given 203 as input.
The below master file is one time prepared and values can be seperated other than comma if required.

203,sm10
304,sm20
0
sk7815
Asked:
sk7815
  • 3
  • 3
  • 2
  • +1
1 Solution
 
AriMcCommented:
Is that really for MS-DOS like specified in your question zone, or a command prompt of some Windows version?



0
 
sjklein42Commented:
Assuming your data is in file "foo.dat" and this command line is in batch file "foo.bat"

@FOR /F "tokens=1,2 delims=," %%i IN (foo.dat) DO @IF "%%i" == "203" echo %%j

Open in new window


c:\temp>foo.bat
sm10

Open in new window


You didn't say what you wanted to do with the "sm10" once you got it, but substitute any command for the "echo".

0
 
sk7815Author Commented:
Excellent!  Thank you so much!  Actually I wanted to get the email ID of the person searching for his ID in a file and this meets the need!
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
Steve KnightIT ConsultancyCommented:
I know this is answered and working fine, but if you use a FIND command it will be quicker than a for loop if there are lots of entries as FIND will bring in only the one correct line:

@echo off
for /f "tokens=2 delims=," %%a in ('find "203" ^<yourfile.txt') do set email=%%a
echo The address is %email%
Steve
0
 
sjklein42Commented:
nice trick
0
 
sk7815Author Commented:
thanks Dragon.  I use %1 or the input from the user and getting FIND parameter is invalid.  

@echo off
for /f "tokens=2 delims=," %%a in ('find %1 ^<foo.dat') do set email=%%a
echo The address is %email%

Output:
C:\junk>foo 203
FIND: Parameter format not correct
The address is
0
 
Steve KnightIT ConsultancyCommented:
You probably just need to put " " around it, try "%~1" - the ~ removes any existing " " first.

Steve
0
 
Steve KnightIT ConsultancyCommented:
You can get more complicated with findstr too, e.g. /b to say beginning a line.
0
 
sk7815Author Commented:
Thank you, it worked with " " .
0

Featured Post

NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

  • 3
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now