Например, я нахожусь в C:\test1
, и у меня есть другой каталог C:\test2\sub2
Я хочу инструмент командной строки, может переключиться на sub2
быстро как это:
quickchange sub2
... и эта программа может установить базу данных справочника для всего диска и обновить базу данных вручную.
Так, есть ли подходящий инструмент для моих требований в командной строке Windows?
(PS: Я не хочу использовать cygwin),
Править: Я хочу, чтобы программа смогла искать базу данных для нахождения где sub2
находится и изменение в нем. Если несколько каталогов соответствуют, это должно попросить, чтобы я выбрал.
Я знаю, что мелкий инструмент под названием QCD может сделать задание, но QCD не обновил в течение долгого времени и имеет некоторые ошибки.
Вы на самом деле не можете сделать этого. Это довольно невозможно от технического аспекта.
Предположите, что у Вас была структура папок как это:
School Work/
English/
Assignments/
Class Work/
Documents/
Science/
Assignments/
Class Work/
Documents/
Math/
Assignments/
Class Work/
Documents/
Теперь, Если Вы работали quickchange Documents
из папки School Work, в какую папку Вы ожидали бы переходить? Существует три соответствия и никакой способ знать, до какого Вы на самом деле хотите добраться. Несомненно, это смогло предлагать Вам, относительно которой папки Вы после, но это не масштабируется очень хорошо
Вообразите эту ту же структуру папок для каждого студента в школе на сервере, таким образом, она выглядит примерно так:
Josh Hunt\
School Work\
[etc]
Cathy Wells\
School Work\
[etc]
Jack Thompson\
School Work\
[etc]
James Smith\
School Work\
[etc]
[repeat for all 1300 students]
Очевидно, это не масштабируется хорошо. Существует теперь 3 900 папок Documents.
Единственный возможный способ сделать перешедшие папки легче использует заполнение клавишей Tab. Вы использовали бы его как это:
/Schoolwork/$ dir E<tab>[nglish/]A<tab>[ssignments/]
Просто для уточнения, <tab>
указывает на Вас нажимающий кнопку вкладки на клавиатуре, тогда как [nglish/]
указывает на то, что заполнение клавишей Tab заполнило для Вас.
Я записал a cd
замена в Perl более чем десятилетие назад, который дает Вам подобные ksh функции (например, CDPATH, CD - $OLDPWD) в строке команды DOS. Можно сделать все с ним кроме заполнения клавишей Tab, которое это не может сделать, потому что это не замена оболочки, это - a cd
замена, поэтому когда Вы совершаете нападки <TAB>
Вы все еще находитесь под командным процессором. Я должен был бы очистить код немного (таким образом, я не смущен; это - горное тело с точки зрения ошибок), но я могу отправить его, если Вам интересно.
Вот встроенная справка для него:
=============================================================================
cdp - provides UNIX-style cd capabilities under Win32
Copyright (C) 1997-8, Joseph L. Casadonte Jr. All rights reserved.
Version: 2.12
Usage: cdp [-h | -help]
cdp -
cdp [-x] [-unix | -dos]
cdp [-x] -quote <AbsolutePathName>
cdp [-x] -quote [-look <dir> | -exc <dir>] <Target>
cdp [-x] <oldpart> <newpart>
cdp [-x] [-noquote] <AbsolutePathName>
cdp [-x] [-noquote] [-look <dir> | -exc <dir>] <Target>
Commands are interpretted in the order given above. Note: the presence of
the -[no]quote option affects the order.
options:
-h Get help (this message) and exit
-help Get help (this message) and exit
-x suppresses the evaluation of $CDP.
-dos cdp with no arguments echos current working directory
-unix cdp with no arguments changes to root of current directory
[default: -unix]
-quote will assume multiple words in <Target> or <AbsolutePathName>
are quoted together (i.e. program files will be interpreted
as 'program files'). May be negated (-noquote). Used mainly with
$CDP (see below). [default: -noquote]
-look <dir> will attempt to find a matching directory by appending <dir>
to each element of $CDPATH\<Target>, or failing that, by
matching an element of $CDPATH\<Target> itself. May be
specified more than once:
cdp -look foo -look bar perl5
Cannot be used in conjunction with -exc. Used mainly with
$CDP (see below).
-exc <dir> will look exclusively for a matching directory by appending
<dir> to each element of $CDPATH\<Target>. If no exact
match is found it will *not* match to an element of
$CDPATH\<Target> alone. Cannot be used in conjunction with
-look. Used mainly with $CDP (see below).
cdp -
-----
Will change to the immediately previous directory ala UNIX by using the
$OLDPWD environment variable.
cdp [-unix | -dos]
------------------
Will either change to the root directory (-unix option) or echo the current
directory (-dos option).
cdp [-quote] <AbsolutePathName>
-------------------------------
Will attempt to change into the directory <AbsolutePathName>. Note:
<AbsolutePathName> is anything that begins with a drive letter (e:\foo), a
front- or back-slash (\temp) or a period (../foo).
cdp [-quote -look <dir> -exc <dir>] <Target>
--------------------------------------------
cdp will use the environment variable $CDPATH to find a valid directory to
change into by appending <Target> to each element in $CDPATH until a match is
found. $CDPATH (or %CDPATH% for the dos-heads) is a semi-colon delimited
list of directories. Directories with spaces in them are fine
(i.e. c:\program files) but UNC names are not (i.e. \\machine\share). The
order of the directories in $CDPATH is important, as the first match wins.
Once a valid directory is found, cdp will change to that directory,
changing drives if necessary. cdp will not match the current working
directory.
You may include the current directory in the CDPATH environment variable by
using the '.' (i.e. set CDPATH=.;c:\my documents;d:\source). Most people
will put this at the very beginning of their CDPATH. It is also extremely
useful if using aliasing (see below).
The two options, -look and -exc, provide ways of extending the match criteria.
If you always change into the source directory of a project (xxx\src), then
you can put the option "-look src" in your $CDP variable, to always look for
a "src" directory when a match on <Target> is found. Multiple "-look <dir>"
options are resolved in the order given on the command line. If none are
found, the match to <Target> alone stands. The "-exc <dir>" option is used to
look exclusively for a particular match to <Target>\<dir>. If one is not
found, no match is returned (i.e. <Target> alone will not match). See the
Examples below for more info.
cdp <oldpart> <newpart>
-----------------------
You can substitute a piece of the current directory name specified by <oldpart>
with <newpart>. For example, if you were in the directory:
c:\release\really\long\directory\structure\src
you could type:
cd release debug
and find yourself in:
c:\debug\really\long\directory\structure\src
assuming it exists. See examples below.
=============================================================================
Examples
========
Given the following directory structure:
e:\program files
e:\program files\perl5
e:\program files\perl5\docs
e:\program files\perl4
e:\program
e:\program\perl5
e:\program\perl5\docs
e:\files
e:\files\perl5
e:\files\perl5\docs
and the following Environment Variables:
set CDPATH=.;e:;e:\program files
set CDP=-quote
set OLDPWD=e:\files\perl5
this command in this directory will result in this
----------------- --------------------- -------------------------
cdp perl5 c:\ e:\program files\perl5
cdp perl5 e:\program files e:\program files\perl5
cdp perl5 e:\program e:\program\perl5
cdp e:\files\perl5 <anywhere> e:\files\perl5
cdp \program e:\<anywhere> e:\program
cdp ..\perl5 e:\program files\perl4 e:\program files\perl5
cdp -unix e:\program files\perl5 e:\
cdp -dos e:\program files\perl5 e:\program files\perl5
cdp - <anywhere> e:\files\perl5
cdp program files e:\program\perl5 e:\program files
cdp -x program files e:\program\perl5 e:\files\perl5
cdp 'program files' e:\program\perl5 e:\program files
cdp -noquote 'program files' e:\program\perl5 e:\program files
cdp -noquote program files e:\program\perl5 e:\files\perl5
cdp -x -quote program files e:\program\perl5 e:\program files
cdp -look docs perl5 c:\ e:\program files\perl5\docs
cdp -look docs perl4 c:\ e:\program files\perl4
cdp -exc docs perl5 c:\ e:\program files\perl5\docs
cdp -exc docs perl4 c:\ cdp: path not found
=============================================================================
Backslash ('\') vs. Frontslash ('/')
====================================
cdp allows you to use, and even mix, backslashes and frontslashes together.
The following are identical:
cdp c:\program files\perl5
cdp c:/program files/perl5
cdp c:\program files/perl5
cdp c:/program files\perl5
=============================================================================
Aliasing
========
It is possible to alias the DOS command 'cd' to be cdp. This way, you
use the features of cdp without having to remember to type a seperate
command. To do this, you need to use a DOSKEY macro. For example:
doskey cd=cdp $*
The "$*" tells DOSKEY to pass all the arguments it received to the new program.
To remove the alias, type:
doskey cd=
If you ever need to invoke the regular DOS 'cd' command, you can always use
'chdir'.
For more information, type:
doskey /?
=============================================================================
Environment Variables
=====================
Note: Environment Variables are case sensitive for Perl.
CDPATH - semi-colon delimited list of directories to search thru
[default: "."]
[$CDPATH: ".;c:\my documents;l:\gc3\glog_deploy\web\xsl;l:\gc3\glog_deploy\web;l:\gc3\glog\server;l:\gc3\glog\oracle;c:\sandbox;c:\my documents\home_page;\;"]
CDP - a set of default options to be used each time cdp is invoked. This
is so you do not have to specify the same options every time you use
cdp.
These options are processed *before* any options on the command line, and
can be overridden (i.e. if -quote is set in $CDP, -noquote on the command
line overrides it). The use of $CDP can be suppressed by specifying
the -x option on the command line.
[$CDP: "-quote"]
CDPFNAME - filename to be used by the Perl script to communicate with the
surrounding batch script (this is a serious hack!). Can be changed
at the top of the script.
[$CDPFNAME: "c:\temp\cdpath.bat"]
TEMP - used by the scripts to create $CDPFNAME.
[$TEMP: "c:\temp"]
OLDPWD - used to store the previous directory (see "cdp -" invocation)
=============================================================================
Files used
==========
%TEMP%\cdpath.bat - file used by the Perl script to communicate with the
surrounding batch script. Can be changed to whatever
is needed at the top of the script.
=============================================================================
Contacting the Author/Latest Version
====================================
Please send questions, bug reports and comments to: joc@netaxs.com
You can get the latest version at: http://www.netaxs.com/~joc/perl.html
=============================================================================
=============================================================================
Вы могли бы также использовать 'subst'
Это позволяет нам, Вы присваиваете букву диска каталогу. Таким образом, можно установить каталог \my stuff\whatever\dunno\something', чтобы быть X: и можно установить '\more stuff\not что stuff\but\this stuff\к Y:
Теперь можно просто использовать букву диска, чтобы сделать весь материал, который Вы обычно делали бы.
Можно использовать ColorConsole среди большого количества других положительных героев, Вы получите интерфейс с вкладками со много CMD и любимыми командами, который делает жизнь НАМНОГО легче.
ColorConsole является бесплатным программным обеспечением, и портативное устройство (не требует установки).
Использовать pushd
и popd
.
C:\Documents and Settings\~quack> pushd d:\foo
D:\foo> pushd e:\bar
E:\bar> popd
D:\foo> popd
C:\Documents and Settings\~quack>
pushd
продвигает Ваш текущий каталог на стек, затем cd
к каталогу аргумента. Стек может быть столь большим, как Вы хотите. popd
удаляет каталог на вершине стека и cd
к нему.
например, я нахожусь в c:\test1, и у меня есть другой каталог c:\test2\sub2
Я принимаю
c:\test1>cd c:\test2\sub2
разве опция не?
Можно всегда использовать историю для переключения между каталогами (нажмите F7).
Я хочу инструмент командной строки, может переключиться на sub2 быстро как это:
quickchange sub2
и эта программа может установить базу данных справочника для всего диска и обновить базу данных вручную.
И если существует (и мы всегда предполагаем, что будет), два каталога под названием "sub2"? Этому понятию точно не понравится это.
таким образом есть ли подходящий инструмент для моего требовать в командной строке Windows?
Существует что-то подобное, см. pushd и popd в Вашей справке cmd. Они позволяют Вам быстро переключиться между двумя каталогами.
Посмотрите здесь:
C:\test1>pushd c:\test2\sub2
c:\test2\sub2>pushd C:\test1
C:\test1>popd
c:\test2\sub2>popd
... to infinity
но у Вас все еще будут проблемы при переключении между несколькими каталогами.
(PS: Я не хочу использовать cygwin),
Попробуйте что-то вроде этого:
@ECHO OFF
goto %1
:docs
cd c:\Users\Phoshi\Documents
GOTO END
:userdir
cd c:\users\Phoshi
GOTO END
:programfiles
cd "c:\program files"
GOTO END
:startup
cd c:\Users\Phoshi\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
GOTO END
:logs
cd "c:\Program Files\Miranda-IM\Logs\"
GOTO END
:music
cd C:\Users\Phoshi\Audio
GOTO END
:pictures
cd C:\Users\Phoshi\Pictures\
GOTO END
:drop
cd "C:\Users\Phoshi\Documents\Drop Box\"
GOTO END
:system32
cd "C:\Windows\System32\"
goto end
:fallout
cd "c:\Program Files\Bethesda Softworks\Fallout 3\"
goto end
:end
Сохраните его как пакетный файл, выразитесь на Вашем пути (\system32, например), и затем можно ввести, сказать, "идут документы" для движения в документы. Вы могли записать небольшую программу, чтобы помочь управлять ими, если Вы хотите, также.
Определенный пример, который Вы имеете, был бы очень трудным, и вероятно не работал бы, если бы два каталога имели то же имя.