如何將 STDOUT 重定向到 cmd 中的後綴參數?

如何將 STDOUT 重定向到 cmd 中的後綴參數?

我想實現以下目標(偽代碼):

set a = where cmd
cd %a%\..

cmd在 Windows 7 的控制台中輸入一行:

where cmd | cd %there%\..

這也要求提取 的父資料夾的路徑cmd,作為where指向可執行檔的路徑。

「cmd」只是一個佔位符。它可以是“java”、“python”、“dot”或 PATH 上的任何其他實用程式。

到目前為止,我已經能夠透過管道傳輸到剪貼簿:

where $path:java | clip

這就是我陷入困境的地方,因為我無法弄清楚如何透過管道傳輸到後綴而不是前綴。我讀過有關&1>和等運算符的內容>>,但我認為它們沒有幫助。我想某種位置變數和使用&將是一種解決方案,但也許不是那麼優雅...

答案1

cmd... Windows 7 控制台中的一行:

for /F "delims=" %G in ('where cmd') do @echo %~dpG

以上命令僅節目結果;若要變更目前目錄,您可以使用

for /F "delims=" %G in ('where cmd') do @CD /D "%~dpG"

解釋在命令列參數(參數)或在for /?

… In addition, substitution of FOR variable references has been enhanced.
You can now use the following optional syntax:

    %~I         - expands %I removing any surrounding quotes (")
    %~fI        - expands %I to a fully qualified path name
    %~dI        - expands %I to a drive letter only
    %~pI        - expands %I to a path only
    %~nI        - expands %I to a file name only
    %~xI        - expands %I to a file extension only
    %~sI        - expanded path contains short names only
    %~aI        - expands %I to file attributes of file
    %~tI        - expands %I to date/time of file
    %~zI        - expands %I to size of file
    %~$PATH:I   - searches the directories listed in the PATH
                   environment variable and expands %I to the
                   fully qualified name of the first one found.
                   If the environment variable name is not
                   defined or the file is not found by the
                   search, then this modifier expands to the
                   empty string

The modifiers can be combined to get compound results:

    %~dpI       - expands %I to a drive letter and path only
    %~nxI       - expands %I to a file name and extension only
    %~fsI       - expands %I to a full path name with short names only
    %~dp$PATH:I - searches the directories listed in the PATH
                   environment variable for %I and expands to the
                   drive letter and path of the first one found.
    %~ftzaI     - expands %I to a DIR like output line

In the above examples %I and PATH can be replaced by other valid
values.  The %~ syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.

另一種方法需要檔案名稱包括擴展:

for %G in (cmd.exe) do @echo %~$PATH:G

相關內容