Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FINDSTR fails when the search string includes a minus character

I'm going through all JS files recursively and minifying them. However I have to leave some JS files intact.

I've had a lot of success using a combination of for, dir and findstr. But when I wanted to ignore already minified files (files ending with "-min.js") the FINDSTR command broke.

This is the command I've used:

for /f %i in ('dir /b /a-d /s "D:\update" ^| findstr /liv "\admin" ^| findstr /ile ".js" ^| findstr /vile "-min.js" ^| findstr /vile ".min.js"') do echo %i

With the following errors:

FINDSTR: /. ignored
FINDSTR: /j ignored
FINDSTR: Bad command line
FINDSTR: Write error
FINDSTR: Write error
FINDSTR: Write error
FINDSTR: Write error

The problem is surely with the findstr /vile "-min.js" clause however I don't know why hyphen is causing a problem since I'm using the /l (literal) flag.

like image 999
Howie Avatar asked Oct 19 '25 18:10

Howie


2 Answers

The C runtime that is handling the arguments to the findstr executable follows a set of rules. One of the rules is to use the double quotes to protect spaces/special characters inside separate arguments, but, once the command line is tokenized and arguments are identified, the quotes are removed before passing the separate arguments to the main code.

That means that this command

findstr /vile "-min.js"

will be handled inside the executable as

argv[0] = findstr 
argv[1] = /vile
argv[2] = -min.js

and, as findstr accepts argument grouping (as in the /vile) but it also allows arguments starting with both / or -, the -m, -i, -n, -s switches (all valid) are accepted, but -. and -j (unknown) are ignored.

The command line is bad because no search string can be found in the arguments.

The documented (findstr /?) solution is to use the /c:"stringToMatch" syntax

findstr /vile /c:"-min.js"

Or you can use the escape character, so the - is not handled as an option argument initial character

findstr /vile "\-min.js"
like image 65
MC ND Avatar answered Oct 22 '25 03:10

MC ND


An alternative to using escape characters or /c:, I've found findstr also cooperates with leading dashes if you include at least 1 space as prefix (doesn't affect the matches when not searching literally).

findstr /vile " -min.js"
like image 42
goom Avatar answered Oct 22 '25 05:10

goom