"${foo##*.}" 구문은 파일 확장자를 어떻게 얻나요? [복사]

"${foo##*.}" 구문은 파일 확장자를 어떻게 얻나요? [복사]

이 명령이 파일 확장자를 성공적으로 검색하는 이유는 무엇입니까?

file_ext=${filename##*.}

답변1

이것은POSIX 쉘 명령 언어:

${parameter##word}

최대 접두사 패턴을 제거합니다. 패턴을 생성하려면 단어를 확장해야 합니다. 그런 다음 매개변수 확장을 통해 접두사의 가장 큰 부분이 제거된 패턴과 일치하는 매개변수를 생성해야 합니다.

이 특별한 경우에는 ( 모든 항목과 일치) *.로 끝나는 가장 큰 하위 문자열로 확장되고 가장 큰 하위 문자열이 제거됩니다. 그래서 파일 확장자만 남습니다..*

파일 이름에 포함된 내용이 없으면 아무 것도 삭제되지 않으므로 .스크립트에서 사용할 때 주의하세요. 동작이 예상한 것과 다를 수 있습니다.

답변2

살펴보십시오 man bash(또는 사용 중인 쉘이 무엇이든):

   ${parameter##word}
          Remove matching prefix pattern.  The word is expanded to produce
          a pattern just as in pathname expansion.  If the pattern matches
          the  beginning 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 pat‐
          tern (the ``##'' case) deleted.  If parameter is  @  or  *,  the
          pattern  removal operation is applied to each positional parame‐
          ter in turn, and the expansion is the resultant list.  If param‐
          eter  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.

따라서 귀하의 경우에는 마지막 "." 이전의 모든 항목이 제거됩니다. 파일의 확장자가 되는 나머지 문자열을 반환합니다.

관련 정보