Using 'find' to return filenames without extension

前端 未结 9 1511
无人及你
无人及你 2020-12-15 22:37

I have a directory (with subdirectories), of which I want to find all files that have a \".ipynb\" extension. But I want the \'find\' command to just return me these filenam

相关标签:
9条回答
  • 2020-12-15 23:05
    find . -type f -iname "*.ipynb" | grep -oP '.*(?=[.])'
    

    The -o flag outputs only the matched part. The -P flag matches according to Perl regular expressions. This is necessary to make the lookahead (?=[.]) work.

    0 讨论(0)
  • 2020-12-15 23:09

    Another easy way which uses basename is:

    find . -type f -iname '*.ipynb' -exec basename -s '.ipynb' {} +
    

    Using + will reduce the number of invocations of the command (manpage):

    -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. For this reason -exec my-command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true.

    Using -s with basename runs accepts multiple filenames and removes a specified suffix (manpage):

    -a, --multiple

    support multiple arguments and treat each as a NAME

    -s, --suffix=SUFFIX

    remove a trailing SUFFIX; implies -a

    0 讨论(0)
  • 2020-12-15 23:10

    If you need to have the name with directory but without the extension :

    find .  -type f -iname "*.ipynb" -exec sh -c 'f=$(basename $1 .ipynb);d=$(dirname $1);echo "$d/$f"' sh {} \;
    
    0 讨论(0)
提交回复
热议问题