英文:
Ensuring a single colon at start of string
问题
我正在使用getopts来解析选项。我想确保optstring
在开头只有一个冒号,如果不存在,我想引入它。
以下是optstring的初始化示例:
local optstring="sn:z:"
英文:
I am using getopts to parse options. I want to ensure that the optstring
has only a single colon at the start, and if this does not exist I want to introduce it.
Here is an example of the initialisation of optstring
local optstring="sn:z:"
答案1
得分: 1
这是与POSIX兼容的代码(在Bash和Dash中进行了测试),处理字符串开头的任意数量的冒号:
optstring=:${optstring#${optstring%%[!:]*}}
${optstring%%[!:]*}
展开为$optstring
开头的冒号字符串(可能为空)。这是通过删除第一个非冒号字符([!:]
)及其后的所有内容来实现的。${optstring#${optstring%%[!:]*}}
展开为删除了开头所有冒号的$optstring
。
这个转换可以分为两个步骤来执行,以增加可读性(可能):
colons=${optstring%%[!:]*}
optstring=:${optstring#$colons}
另一种(也与POSIX兼容的)方法是使用循环删除开头的冒号:
while [ "${optstring#:}" != "$optstring" ]; do
optstring=${optstring#:}
done
optstring=:$optstring
英文:
This POSIX-compatible code (tested with Bash and Dash) handles arbitrary numbers of colons at the start of the string:
optstring=:${optstring#${optstring%%[!:]*}}
${optstring%%[!:]*}
expands to the (possibly empty) string of colons at the start of$optstring
. It does this by removing the first non-colon character ([!:]
) and everything that follows it.${optstring#${optstring%%[!:]*}}
expands to$optstring
with all the colons at the start removed.
The transformation can be done in two steps to (possibly) make it more readable:
colons=${optstring%%[!:]*}
optstring=:${optstring#$colons}
Another (also POSIX-compatible) approach is to use a loop to remove leading colons:
while [ "${optstring#:}" != "$optstring" ]; do
optstring=${optstring#:}
done
optstring=:$optstring
答案2
得分: 0
首先,我们无条件地添加一个冒号,然后我们使用参数扩展来扩展我们的字符串,删除任何已存在的冒号。
英文:
optstring=:${optstring#:}
First we unconditionally add a colon, then we use a parameter expansion to expand our string with any preexisting colon removed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论