Using 'find' to return filenames without extension

前端 未结 9 1623
无人及你
无人及你 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条回答
  •  旧时难觅i
    2020-12-15 22:52

    To return only filenames without the extension, try:

    find . -type f -iname "*.ipynb" -execdir sh -c 'printf "%s\n" "${0%.*}"' {} ';'
    

    or (omitting -type f from now on):

    find "$PWD" -iname "*.ipynb" -execdir basename {} .ipynb ';'
    

    or:

    find . -iname "*.ipynb" -exec basename {} .ipynb ';'
    

    or:

    find . -iname "*.ipynb" | sed "s/.*\///; s/\.ipynb//"
    

    however invoking basename on each file can be inefficient, so @CharlesDuffy suggestion is:

    find . -iname '*.ipynb' -exec bash -c 'printf "%s\n" "${@%.*}"' _ {} +
    

    or:

    find . -iname '*.ipynb' -execdir basename -s '.sh' {} +
    

    Using + means that we're passing multiple files to each bash instance, so if the whole list fits into a single command line, we call bash only once.


    To print full path and filename (without extension) in the same line, try:

    find . -iname "*.ipynb" -exec sh -c 'printf "%s\n" "${0%.*}"' {} ';'
    

    or:

    find "$PWD" -iname "*.ipynb" -print | grep -o "[^\.]\+"
    

    To print full path and filename on separate lines:

    find "$PWD" -iname "*.ipynb" -exec dirname "{}" ';' -exec basename "{}" .ipynb ';'
    

提交回复
热议问题