найти все файлы с определенными расширениями и выполнить - PullRequest
0 голосов
/ 26 февраля 2019

Почему при запуске этой команды появляется сообщение об ошибке: «Нет такого файла или каталога?»

for i in `find ~/desktop -name '*.py'` ; do ./$i ;  done

Ответы [ 4 ]

0 голосов
/ 26 февраля 2019

Вы должны использовать $ i, а не ./$i

Я делал то же самое в этот момент.Я хотел, чтобы скрипт нашел, есть ли в каталоге файлы flac, и преобразовал его в opus.

Вот мое решение:

if test -n "$(find ./ -maxdepth 1 -name '*.flac' -print -quit)"
then
    do this
else
    do nothing
fi
0 голосов
/ 26 февраля 2019

Полное сообщение об ошибке значительно упрощает проблему:

bash: .//home/youruser/desktop/foo.py: No such file or directory

Вы видите, что такого файла действительно нет:

$ .//home/youruser/desktop/foo.py
bash: .//home/youruser/desktop/foo.py: No such file or directory

$ ls -l .//home/youruser/desktop/foo.py
ls: cannot access './/home/youruser/desktop/foo.py': No such file or directory

Вот как выможно запустить файл /home/youruser/desktop/foo.py:

$ /home/youruser/desktop/foo.py
Hello World

Таким образом, чтобы запустить его в цикле, вы можете сделать:

for i in `find ~/desktop -name '*.py'` ; do $i ;  done

Вот лучший способ сделать то же самое:

find ~/desktop -name '*.py' -exec {} \;

или с циклом оболочки:

find ~/desktop -name '*.py' -print0 | while IFS= read -d '' -r file; do "$file"; done

Объяснение того, что такое ./, и почему оно здесь не имеет смысла, см. этот вопрос

0 голосов
/ 26 февраля 2019

Пути, возвращаемые оператором find, будут абсолютными путями, например ~ / desktop / program.py.Если вы поставите ./ перед ними, вы получите пути типа ./~/desktop/, которые не существуют.

Заменить ./$i на "$i" (кавычки, чтобы заботиться об именах файлов с пробелами и т. Д.).

0 голосов
/ 26 февраля 2019

Попробуйте найти и exec вариант.http://man7.org/linux/man-pages/man1/find.1.html

   -exec command ;
          Execute command; true if 0 status is returned.  All following
          arguments to find are taken to be arguments to the command
          until an argument consisting of `;' is encountered.  The
          string `{}' is replaced by the current file name being
          processed everywhere it occurs in the arguments to the
          command, not just in arguments where it is alone, as in some
          versions of find.  Both of these constructions might need to
          be escaped (with a `\') or quoted to protect them from
          expansion by the shell.  See the EXAMPLES section for examples
          of the use of the -exec option.  The specified command is run
          once for each matched file.  The command is executed in the
          starting directory.  There are unavoidable security problems
          surrounding use of the -exec action; you should use the
          -execdir option instead.

   -exec command {} +
          This variant of the -exec action runs the specified command on
          the selected files, but the command line is built by appending
          each selected file name at the end; the total number of
          invocations of the command will be much less than the number
          of matched files.  The command line is built in much the same
          way that xargs builds its command lines.  Only one instance of
          `{}' is allowed within the command, and (when find is being
          invoked from a shell) it should be quoted (for example, '{}')
          to protect it from interpretation by shells.  The command is
          executed in the starting directory.  If any invocation with
          the `+' form returns a non-zero value as exit status, then
          find returns a non-zero exit status.  If find encounters an
          error, this can sometimes cause an immediate exit, so some
          pending commands may not be run at all.  This variant of -exec
          always returns true.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...