How do we match the suffix in a string in bash?

I want to check if the input parameter ".c" ends? How can I check this? Here is what I got so far (thanks for your help):

#!/bin/bash for i in $@ do if [$i ends with ".c"] then echo "YES" fi done 
+6
source share
3 answers

Classic case for case !

 case $i in *.c) echo Yes;; esac 

Yes, the syntax is secret, but you will get used to it quickly. Unlike the various Bash and POSIX extensions, this is fully ported back to the original Bourne shell.

+9
source
 $ [[ foo.c = *.c ]] ; echo $? 0 $ [[ foo.h = *.c ]] ; echo $? 1 
+8
source
 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 jpaugh ):

  • Iterating over command line arguments: for i in $@ ; do for i in $@ ; do
  • The main trick here: if [ -z ${i##*.c} ]; then if [ -z ${i##*.c} ]; then . Here we check if the string length ${i##*.c} is equal to zero. ${i##*.c} means: take the value of $ i and remove the substring according to the pattern "* .c". If the result is an empty string, then we have the suffix .c ".

Here, if there is any additional information from a human bash, the section Parameter Expasion

 ${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. 
+1
source

Source: https://habr.com/ru/post/899508/


All Articles