Rajat Saxena
Rajat Saxena

Reputation: 3935

windows batch programming: Removing only exactly matching line from the file

I have a file like this:

exit;
exit_cool
int exit =30
exitstatus;
exit ;
 exit;
some exit;
coolexit;
this line should not be removed.
exitexit;

I want to remove the line which contains only "exit;" from this file.So I want the command to remove only the first line from the file.I'm using this command currently:

type somefile.txt | find /v "exit;"

but the output I'm getting is:

exit_cool
int exit =30
exitstatus;
exit ;
this line should not be removed.

As you have seen the command removed all the lines containing exit;.I only want line 1 to be removed as it is the exact match.Any help?

Upvotes: 0

Views: 1110

Answers (2)

dbenham
dbenham

Reputation: 130919

FIND cannot do what you want. But FINDSTR can :-)

Using FINDSTR with regular expression anchors ^ for the beginning of a line, and $ for the end of a line:

findstr /v "^exit;$" "somefile.txt"

Or using the /x option that has the exact same meaning, but can also be used with string literals, not just regular expressions:

findstr /v /x /c:"exit;" "somefile.txt"

Note that the end of line $ anchor and /x option (and /e end option) only work properly when the text file uses Windows style lines that are terminated by carriage return/line feed. Unix style lines that end simply with line feed will not work properly.

Upvotes: 1

Saju
Saju

Reputation: 3267

Use findstr command. instead of find It is better and it takes regular expressions also.

type somefile | findstr /v "^exit;"

or

findstr /v "^exit;" somefile

good luck

Upvotes: 0

Related Questions