Использует для этого метода извлечения имени файла bash? - PullRequest
9 голосов
/ 11 февраля 2009

У меня есть часть скрипта bash, которая получает имя файла без расширения, но я пытаюсь понять, что на самом деле здесь происходит. Для чего "%%"? Может кто-нибудь рассказать о том, что Bash делает за кулисами? Как эту технику можно использовать на общих основаниях?

#!/bin/bash

for src in *.tif
    do
    txt=${src%%.*}
    tesseract ${src} ${txt}
    done

Ответы [ 5 ]

15 голосов
/ 11 февраля 2009

Избавляется от расширения имени файла ( здесь : .tif), пример:

$ for A in test.py test.sh test.xml test.xsl; do echo "$A: ${A%%.*}"; done
test.py: test
test.sh: test
test.xml: test
test.xsl: test

из руководства по bash:

   ${parameter%%word}
          The word is expanded to produce a pattern just as in pathname expansion.  If the
          pattern matches a trailing portion of the expanded 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.
4 голосов
/ 11 февраля 2009

Вот вывод со страницы руководства bash

 ${parameter%%word}
          The word is expanded to produce a pattern just  as  in  pathname
          expansion.   If  the  pattern  matches a trailing portion of the
          expanded value of parameter, then the result of the expansion is
          the  expanded value of parameter with the shortest matching pat-
          tern (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.
3 голосов
/ 11 февраля 2009

Очевидно, bash имеет несколько инструментов " Расширение параметров ", которые включают в себя:

Простая подстановка значения ...

${parameter}

Расширение до подстроки ...

${parameter:offset}
${parameter:offset:length}

подставить длину значения параметра ...

${#parameter}

Расширение после совпадения в начале параметра ...

${parameter#word}
${parameter##word}

Расширение после совпадения в конце параметра ...

${parameter%word}
${parameter%%word}

Расширяет параметр для поиска и замены строки ...

${parameter/pattern/string}

Это моя интерпретация частей, которые, как мне кажется, я понимаю из этого раздела справочных страниц. Дайте мне знать, если я пропустил что-то важное.

1 голос
/ 11 февраля 2009

Это операция удаления строки в формате: ${str%%substr}

Где str - строка, с которой вы работаете, а substr - шаблон для сопоставления. Он ищет самое длинное соответствие substr в str и удаляет все с этого момента.

1 голос
/ 11 февраля 2009

Проверьте "Расширение параметров" в справочных страницах bash. Этот синтаксис расширяет переменную $ src, удаляя из нее материал, соответствующий шаблону. *.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...