Linux Shell字符串中的百分号有什么作用?

Linux Shell字符串中的百分号有什么作用?

When you are in the process of learning how to fully use the Linux shell, you may find yourself curious about how much you can manipulate strings in order to get the best results. With that in mind, today’s SuperUser Q&A post has the answer to a curious reader’s question.

当您学习如何完全使用Linux shell时,您可能会发现自己对可以操纵字符串以获得最佳结果的方式感到好奇。 考虑到这一点,今天的SuperUser Q&A帖子回答了一个好奇的读者的问题。

Today’s Question & Answer session comes to us courtesy of SuperUser—a subdivision of Stack Exchange, a community-driven grouping of Q&A web sites.

今天的“问答”环节由SuperUser提供,它是Stack Exchange的一个分支,该社区是由社区驱动的Q&A网站分组。

问题 (The Question)

SuperUser reader Nissim Kaufmann wants to know what the percent sign in Linux shell strings does:

超级用户读者Nissim Kaufmann想知道Linux Shell字符串中的百分号是做什么的:

When using the Linux shell, what does the percent sign (%) do? For example:

使用Linux Shell时,百分号(%)有什么作用? 例如:

Linux Shell字符串中的百分号有什么作用?

What does the percent sign in Linux shell strings do?

Linux Shell字符串中的百分号有什么作用?

答案 (The Answer)

SuperUser contributor Marek Rost has the answer for us:

超级用户贡献者Marek Rost为我们提供了答案:

When the percent sign (%) is used in the pattern ${variable%substring}, it will return content of the variable with the shortest occurrence of substring deleted from the back of the variable.

当在模式$ {variable%substring}中使用百分号(%)时,它将返回该变量的内容,其中从字符串的后面删除的子字符串出现的时间最短。

This function supports wildcard patterns, that is why it accepts an asterisk (star) as a substitute for zero or more characters. It should be mentioned that this is Bash specific. Other Linux shells do not necessarily contain this function.

此功能支持通配符模式,这就是为什么它接受星号(星号)代替零个或多个字符的原因。 应该提到的是,这是Bash特有的。 其他Linux外壳程序不一定包含此功能。

If you want to learn more about string manipulation in Bash, then I highly suggest reading the following page, Advanced Bash-Scripting Guide: Chapter 10. Manipulating Variables. Among many other handy functions, it explains what a double percent sign (%%) does, for example.

如果您想了解有关Bash中的字符串操作的更多信息,那么我强烈建议您阅读以下页面, 高级Bash脚本指南:第10章 。 例如,在许多其他方便的功能中,它解释了双百分号(%%)的作用。

I forgot to mention that when it is used in the pattern $((variable%number)) or $((variable1%$variable2)), the percent sign (%) character will function as a modulo operator.

我忘了提一下,当在$((variable%number))$((variable1%$ variable2))模式中使用它时 ,百分号(%)字符将用作模运算符。

When the percent sign (%) is used in different contexts, it should be recognized as a regular character only.

当百分号(%)在不同的上下文中使用时,应仅将其识别为常规字符。



Have something to add to the explanation? Sound off in the comments. Want to read more answers from other tech-savvy Stack Exchange users? Check out the full discussion thread here.

有什么补充说明吗? 在评论中听起来不错。 是否想从其他精通Stack Exchange的用户那里获得更多答案? 在此处查看完整的讨论线程

Image Credit: Linux Screenshots (Flickr)

图片来源: Linux屏幕截图(Flickr)

翻译自: https://www.howtogeek.com/270333/what-does-the-percent-sign-in-linux-shell-strings-do/