Как нам сопоставить суффикс в строке в bash? - PullRequest
9 голосов
/ 18 октября 2011

Я хочу проверить, заканчивается ли входной параметр ".c"? Как мне это проверить? Вот что я получил (спасибо за вашу помощь):

#!/bin/bash

for i in $@
do
    if [$i ends with ".c"]
    then
            echo "YES"
        fi
done

Ответы [ 3 ]

13 голосов
/ 18 октября 2011

Классический случай для case!

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

Да, синтаксис загадочный, но вы быстро к нему привыкнете.В отличие от различных расширений Bash и POSIX, он переносим вплоть до оригинальной оболочки Bourne.

8 голосов
/ 18 октября 2011
$ [[ foo.c = *.c ]] ; echo $?
0
$ [[ foo.h = *.c ]] ; echo $?
1
1 голос
/ 22 февраля 2018
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
$

Объяснение (спасибо jpaugh ):

  1. Перебрать аргументы командной строки: for i in $@; do
  2. Главный трюк здесь: if [ -z ${i##*.c} ]; then. Здесь мы проверяем, равна ли длина строки ${i##*.c} нулю. ${i##*.c} означает: принять значение $ i и удалить подстроку по шаблону "* .c". Если результат - пустая строка, то у нас есть суффикс ".c".

Здесь, если какая-то дополнительная информация от 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.
...