如何记住哪个扩展${var%}${var#}从哪一端开始工作?
我很难记住哪一个参数扩展${var%subst}或${var#subst}从字符串的前面删除,哪一个从字符串的后面删除。例子:
$ var=/a/b/c
$ echo dirname=${var#/*} filename=${var%%*/}
dirname=a/b/c filename=/a/b/c # Wrong!
$ echo dirname=${var%/*} filename=${var##*/}
dirname=/a/b filename=c
我总是将它们混合在一起,最终要么编写一些测试命令,要么查看手册。很容易记住%%删除 more then %,因为then%%是一个更长的字符串%,2 个字符 vs 1 个字符,与##vs相同#。但我总是%和#.
是否有内存规则可以知道字符串的哪一端%或#从哪一端删除?
回答
百分比符号%总是排在数字的最后(例如86%),因此它们从末尾删除。
散列符号#开始注释,因此它们从开头删除。
- "The #1 rule, useful 100% of the time" - That's the phrase I use. Hence `#` removes from the start because it's at the start, `%` removes from the end for the opposite reason. Then the only complication is greedy/non-greedy mode. Obviously people who want *more* (such as `##` rather than `#`) are greedy.
回答
记住只有 1 和其他将与它相反。
# Shebang 从一个散列开始,这意味着它将从开始直到模式中删除,如果您记得这一点并且您知道恕我直言 🙂