【发布时间】:2021-09-14 15:33:30
【问题描述】:
尝试将我的旧 bat (batch) 文件转换为 sh (bash) 但仍有一些问题我仍然无法找到 sh 等效(for delims tokens 为一)。
最值得注意的是,在 bat 中发现了非常漂亮的参数扩展:
https://ss64.com/nt/syntax-args.html
http://cplusplus.bordoon.com/cmd_exe_variables.html
%~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:1 - searches the directories listed in the PATH
environment variable and expands %1 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:1 - searches the directories listed in the PATH
environment variable for %1 and expands to the
drive letter and path of the first one found
(but this would work only in called functions and
only for numbered variables)
%~ftzaI - expands %I to a DIR like output line
因此对于C:\Users\dkoch\Downloads\test.bat,您会得到:
%~0 : test.bat
%~f0 : C:\Users\dkoch\Downloads\test.bat
%~d0 : C:
%~p0 : \Users\dkoch\Downloads\
%~n0 : test
%~x0 : .bat
%~s0 : C:\Users\dkoch\DOWNLO~1\test.bat
%~a0 : --a--------
%~t0 : 14/09/2021 17:58
%~z0 : 351
%~$PATH:1 :
%~dp0 : C:\Users\dkoch\Downloads\
%~nx0 : test.bat
%~fs0 : C:\Users\dkoch\DOWNLO~1\test.bat
%~dp$PATH:1 :
%~ftza0 : --a-------- 14/09/2021 17:58 351 C:\Users\dkoch\Downloads\test.bat
如果可以的话,我经常使用%~f1 之类的东西来尝试将第一个参数扩展为完整路径。否则,参数保持不变并按原样传递。
sh中是否有类似$~f1这样方便的东西?
到目前为止,我发现的所有内容都是变量子字符串提取/替换:
http://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Expansions
https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html
https://linuxhint.com/bash_parameter_expansion/
https://wiki.bash-hackers.org/syntax/pe
对我正在尝试做的事情没有帮助。你的选择?
问候。
【问题讨论】:
-
现在这个问题的提问方式只有 bash和bat都懂的人才可以回答。
-
你能以一种不假设读者知道
%~f1的意思的方式来写它吗? -
(...如果只是将相对路径变成绝对路径,这就是
readlink -f或realpath的用途)。 -
关键是那些不是你的人不知道“至少蝙蝠做什么”是,所以我们不能告诉你什么要求。鉴于上面评论中的猜测,听起来你自己并不完全知道“至少蝙蝠做什么”。
-
AFAIK,@Socowi 的答案应该完全解决您的问题,但如果没有,也许您可以/应该评论它,描述它如何以及为什么没有?
标签: bash batch-file parameter-expansion