我们如何在 bash 中匹配字符串中的后缀?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7802763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do we match a suffix in a string in bash?
提问by Dave
I want to check if an input parameter ends with ".c"? How do I check that? Here is what I got so far (Thanks for your help):
我想检查输入参数是否以“.c”结尾?我如何检查?这是我到目前为止得到的(感谢您的帮助):
#!/bin/bash
for i in $@
do
if [$i ends with ".c"]
then
echo "YES"
fi
done
回答by tripleee
A classical case for case!
一个经典案例case!
case $i in *.c) echo Yes;; esac
Yes, the syntax is arcane, but you get used to it quickly. Unlike various Bash and POSIX extensions, this is portable all the way back to the original Bourne shell.
是的,语法很神秘,但你很快就会习惯它。与各种 Bash 和 POSIX 扩展不同,它可以一直移植到原始的 Bourne shell。
回答by Ignacio Vazquez-Abrams
$ [[ foo.c = *.c ]] ; echo $?
0
$ [[ foo.h = *.c ]] ; echo $?
1
回答by Alexey Kondakov
for i in $@; do
if [ -z ${i##*.c} ]; then
echo "YES: $i"
fi
done
$ ./test.sh .c .c-and-more before.c-and-after foo.h foo.c barc foo.C
YES: .c
YES: foo.c
$
Explanation (thanks to jpaugh):
解释(感谢jpaugh):
- Iterate over command line arguments:
for i in $@; do - Main trick is here:
if [ -z ${i##*.c} ]; then. Here we check if length of string${i##*.c}is zero.${i##*.c}means: take $i value and remove substring by template "*.c". If result is empty string, then we have ".c" suffix.
- 迭代命令行参数:
for i in $@; do - 主要技巧在这里:
if [ -z ${i##*.c} ]; then. 这里我们检查字符串的长度${i##*.c}是否为零。${i##*.c}意思是:取 $i 值并通过模板“*.c”删除子字符串。如果结果是空字符串,那么我们有“.c”后缀。
Here if some additional info from man bash, section Parameter Expasion
在这里,如果来自 man bash 的一些附加信息,参数扩展部分
${parameter#word}
${parameter##word}
Remove matching prefix pattern. The word is expanded to produce a pat‐
tern just as in pathname expansion. If the pattern matches the begin‐
ning of the value of parameter, then the result of the expansion is the
expanded value of parameter with the shortest matching pattern (the
``#'' case) or the longest matching pattern (the ``##'' case) deleted.
If parameter is @ or *, the pattern removal operation is applied to
each positional parameter in turn, and the expansion is the resultant
list. If parameter is an array variable subscripted with @ or *, the
pattern removal operation is applied to each member of the array in
turn, and the expansion is the resultant list.

