PeterS
PeterS

Reputation: 724

How to pass multiple values in a single variable using batch file

I want to pass multiple values in a variable. Here's my code

@echo off
setlocal EnableDelayedExpansion
set LF=^


set "content="

for /f "delims=" %%x in (file.txt) do (
  set "content=!content!%%x!LF!" 
  Type paul.txt  | findstr /I /V /C:"!content!" > edit.txt
)

echo(!content!

PAUSE

endlocal

Basically, this code opens the file file.txt and the contents of this file were used and pass to variable "content".

Example:

file.txt contains the ff:

A
B

So, all lines starting A or B on file paul.txt will be removed but no lines were removed. What's wrong with this code?

Upvotes: 0

Views: 2090

Answers (3)

dbenham
dbenham

Reputation: 130819

Ouch! You are going about this completely wrong. First I will list some errors. Then I will show you a very simple solution.

1) There is no need to place all the lines in a single variable. Each line represents an independent search term. Putting all lines (including linefeeds) in a variable and using that in /C:string option treats the entire content as a single search term that tries to match the file content with the entire term, including the linefeeds.

2) Even if you really did want all lines in a single variable, your logic is wrong. You are executing your FINDSTR upon each iteration, but you only want to execute it once after the variable is completely populated.

3) The delayed expansion is not working as you expect because you are attempting to use it with a pipe - the value is getting expanded too early. See https://stackoverflow.com/a/8194279/1012053.

4) You state you want to exclude lines that begin with the file content. You need to instruct FINDSTR accordingly.

5) Not an error, but there is no need to use a pipe at all. Simply let FINDSTR read paul.txt directly.

And the simple solution:

findstr /viblg:file.txt paul.txt >edit.txt

Note that I have concatenated the FINDSTR options after a single /. This is one of many undocumented FINDSTR features.

The /G:file option instructs FINDSTR to use each line within file as an independent search string.

The /L option forces the search strings to be interpreted as literal strings (as opposed to regular expressions)

The /B option forces the search terms to only match the beginning of a line.

Upvotes: 1

MC ND
MC ND

Reputation: 70923

findstr /l /v /g:file.txt Paul.txt > edit.txt

Find the non matching lines in Paul.txt, reading search strings from file.txt, sending the output to edit.txt

If the match needs to be over the full line, include a /x in the list of arguments

Upvotes: 0

foxidrive
foxidrive

Reputation: 41234

Will this do the job in your situation?

findstr /r /i /v /c:"^A" /c:"^B" file.txt >file2.txt

Upvotes: 0

Related Questions