Future
Future

Reputation: 388

Findstr /g with token or delim

Suppose we have 2 files

First.txt

123
456

And Second.txt

789;123
123;def
482;xaq

What i need is to find the lines in the second file only containing entries of the first file in first column (token 1, delim ; ). This is what i need:

Output.txt

123;def

Of course,

findstr /g:first.txt second.txt

will output both lines:

789;123
123;def

Any idea how i can mix findstr and for /f to get the needed output? Thank you!

Upvotes: 0

Views: 4402

Answers (4)

MC ND
MC ND

Reputation: 70943

Without executing a separate findstr for each value and to avoid the problem with partial matches at the start of the line, you can try with

@echo off
    setlocal enableextensions disabledelayedexpansion

    ( cmd /q /c"(for /f "delims=" %%a in (first.txt) do echo(%%a;)" 
    ) | findstr /g:/ /l /b second.txt

What it does is read first.txt and echo each line with the delimiter. This output is retrieved by the findstr using /g:/ to use the standard input as the source for the elements to match, that will be considered as literals (/l) at the start of the line (/b) in the second.txt file

Upvotes: 2

SomethingDark
SomethingDark

Reputation: 14325

You can take advantage of the super-limited regex capabilities of findstr and compare each line of first.txt to only the very beginning of each line of second.txt.

@echo off
for /F %%A in (first.txt) do findstr /R /C:"^%%A;" second.txt

The /R flag means that the search string should be treated as a regular expression. The ^ in the search string means that %%A comes at the very beginning of the line. The ; is a literal semicolon that will prevent the 123 line from picking up 1234;abcd in second.txt.

Upvotes: 3

Magoo
Magoo

Reputation: 80113

If all of the elements in the first column are of the same length, then the simple answer would be

findstr /b /g:first.txt second.txt

Note however that if first.txt contains a line 12 then this would match 123;abc and 129;pqr in the second file.

Upvotes: 2

Serenity
Serenity

Reputation: 184

Is the general form for CSV. Note in batch %A becomes %%A.

for /f "delims=," %A in (csv.txt) do findstr /c:"%A" file2.txt

Here's the output

C:\Users\User>for /f "delims=," %A in (csv.txt) do findstr /c:"%A" csv1.txt

C:\Users\User>findstr /c:"55" csv1.txt
55,61,hi there, Good

C:\Users\User>findstr /c:"60" csv1.txt
54,60,hi there, Bad

C:\Users\User>findstr /c:"Bad" csv1.txt
54,63,hi there, Bad
54,60,hi there, Bad

C:\Users\User>findstr /c:"55" csv1.txt
55,61,hi there, Good

Contents of two files.

55,60
60,60
Bad,60
55,60

and

55,61,hi there, Good
54,62,hi there, Good
54,63,hi there, Bad
54,60,hi there, Bad

Upvotes: 0

Related Questions