Skip to content

Instantly share code, notes, and snippets.

@deskobj
Last active March 6, 2020 17:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deskobj/4756362 to your computer and use it in GitHub Desktop.
Save deskobj/4756362 to your computer and use it in GitHub Desktop.
Workaround for "One bug in SED.EXE and another in MS-DOS cmd.exe DEL command" -- https://p19z.blogspot.com/2013/02/sed-and-msdos-bugs.html
@rem MODULE ..............: sed4win
@rem AUTHOR ..............: Patryk Szczepankiewicz ( pszczepa [at] gmail [dot] com )
@rem USAGE ...............: You can use this to wrap your sed.exe executable on windows.
@rem Customize this script by creating a %SED_EXE% environment variables
@rem or by editing the 'DEFAULT_SED_LOCATION' variable in this script.
@rem DESCRIPTION .........: The base script should just be a one-liner such as [see blog post]
@rem BUT BUG: 'sed' creates a temporary file in the working directory
@rem ( see: http://sourceforge.net/p/gnuwin32/bugs/477/ )
@rem WORKAROUND: delete the temporary file by pattern /sed[a-zA-Z0-9]{6}/
@rem ... BUT WARNING: in terms of wildcards, "sed??????" is equivalent to "sed*"
@rem because of the way the MSDOS DEL command looks at all the files names as
@rem being 8.3 characters long.
@rem So, the FINAL-WORKAROUND is: do the sed operation while using a temporary
@rem directory as the working directory, and deleting everything at the end.
@rem REFERENCES ..........: http://sourceforge.net/p/gnuwin32/bugs/477/ (Bug ticket)
@rem + https://gist.github.com/deskobj/4756362 (Module's online source)
@rem HISTORY .............: Created FEB 11, 2013
@rem Updated MAR 06, 2020 - Do not use `@echo off` + refine searching of the sed.exe file.
@setlocal
@rem EXECUTABLE LOCATION
@if not defined DEFAULT_SED_LOCATION (
if exist "%ProgramFiles(x86)%\GnuWin32\bin\sed.exe" (
set DEFAULT_SED_LOCATION=%ProgramFiles(x86)%\GnuWin32\bin\sed.exe
) else (
set DEFAULT_SED_LOCATION=%ProgramFiles%\GnuWin32\bin\sed.exe
)
)
@if not defined SED_EXE (
@>NUL &2>1 where sed.exe
@if not errorlevel 1 set SED_EXE=sed.exe
)
@if not defined SED_EXE set SED_EXE=%DEFAULT_SED_LOCATION%
@if not exist "%SED_EXE%" (
goto lblExeNotFound
)
@rem THE ACTUAL WORAROUND
@if not exist "%TEMP%\sed_wd" mkdir "%TEMP%\sed_wd"
@pushd "%TEMP%\sed_wd"
@"%SED_EXE%" %*
@del /q *
@popd
@rmdir /s /q "%TEMP%\sed_wd"
@exit /b
:lblExeNotFound
echo %~n0: ERROR: sed.exe not found.
exit /b 2
@endlocal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment