Skip to content

Instantly share code, notes, and snippets.

@icodebot
Last active August 29, 2015 14:14
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 icodebot/c5e16e9233f6db4e207a to your computer and use it in GitHub Desktop.
Save icodebot/c5e16e9233f6db4e207a to your computer and use it in GitHub Desktop.
cd to the location of a file in system path, and optionally run a command. Finds the file using "where" and then cd's to the directory

Windows command line util to CD to the location of a file found in your system path, and optionally run a command. Finds the file using "where" and then cd's to that directory where the file is located.

Requires: xargs sed

@echo off
echo "%~dp1"
@echo off
SET godir=
FOR /F "tokens=*" %%i in ('%~dp0wherep %1') do SET godir=%%~i
if "%godir%" == "" goto pathnotfound
:setdir
pushd %godir%
:: Command to run?
if "%2"=="" goto :eof
FOR /F "tokens=*" %%i in ('where %1') do SET gofile=%%~i
%2 %gofile%
goto :eof
:pathnotfound
echo %1 not found
goto :eof
:help
echo.
echo gofile <filename> [command]
echo.
echo. Executes where on the file, and sets current directory to where it is located.
echo. use 'popd' to return to previous directory
echo.
@echo off
::Input is to be piped in to this script "where blah.txt | slash"
:: escapes backslash character c:\xxx\yyy\zzz become c:\\xxx\\yyy\\zzz
more | sed s/\\/\\\\/g
@echo off
:: returns the path of a file found on path
where %1 | slash | xargs -I {} getpath {}
@icodebot
Copy link
Author

This could simplified in to fewer command line files.
Requires:
xargs - http://www.gnu.org/software/findutils/findutils.html
sed - http://gnuwin32.sourceforge.net/packages/sed.htm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment