Use awk to grep

I have gawk installed on my Windows 10 machine, but no grep, but still needed to quickly find text in some files.

So I came up with (read: “found on the internet”) this one-liner

@for /f "eol=: delims=" %F in ('dir /b /s [directory]') do
@awk "/[search string]/ {print $0}" %F

Usually I use grepWin for such tasks, but only later realized that a simply Ctrl-C would copy the selected search result to the clipboard – grepWin’s context menu does not have a menu item for this function, even though it has been suggested in a related issue.

I also noticed grepWin has a memory problem if you search huge files on a machine with little RAM. On the other hand, it searches using the Windows codepage rather than the DOS codepage.

Test if Directory exists in Batch file (.cmd)

My previous post on testing network drives led me to further research the topic, and I came to quite surprising (at least for me) results: the result if a check with IF EXIST depend on whether

  • the drive is a local drive or a mapped network drive or a UNC path
  • the path contains spaces or not
  • the path is quoted or not
  • cmd runs in administrator mode or user mode

I wrote a small batch file that contains a couple of assignments of the form

set dir=c:\temp
set dir=c:\temp\with spaces
etc.

and executed these tests on each value

if exist %dir% echo exists
if exist %dir%\nul echo exists
if exist %dir%\. echo exists
if exist "%dir%" echo exists
if exist "%dir%\nul" echo exists
if exist "%dir%\." echo exists

These are the results

directory %dir% %dir%\nul %dir\. “%dir%” “%dir%\nul” “%dir%\.”
local x x x x x
local (spaces) x x
mapped (non-admin) x x x x x
mapped (non-admin, spaces) x x
UNC x x x x x x
UNC (spaces) x x x

Comments:

Testing directory path containing spaces can only be performed using the quoted notation.

Mapped network drives can only be access in non-administrator mode (see these threads).

The only reliable way to test for directory existence is therefore to use the quoted “%dir%\.” notation.

To check whether cmd runs in administrator mode or not, use an admin statement such as ‘at’:

at >nul 2>nul
if errorlevel 1 echo you are not in administrator mode

Test if Network Directory exists in Batch file (.cmd)

The default way to check whether a directory exists in a Windows batch file (.cmd) is

if not exist "%directory%\nul" (
   echo %directory% does not exist
)

However, as this MS KB explains, the check for the NUL file does not work with directories on network drives mapped to a drive letter.

A working solution I found is to process the ERRORLEVEL value a DIR command sets

dir %directory% >nul 2>nul
if errorlevel 1 (
   echo %directory does not exist
)

or

dir %directory% >nul 2>nul
if not errorlevel 1 (
    echo %directory exists
)

Also note that mapped network drives are not available in administrator mode, as is discussed in these threads.