Using 'find' to return filenames without e

2019-02-23 14:55发布

问题:

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 filenames without the extension.

I know the first part:

find . -type f -iname "*.ipynb" -print    

But how do I then get the names without the "ipynb" extension? Any replies greatly appreciated...

回答1:

To return only filenames without the extension, try:

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

or:

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

or:

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

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

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

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 . -name "*.ipynb" -exec sh -c 'printf "%s\n" "${0%.*}"' {} ';'

or:

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

To print full path and filename on separate lines:

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


回答2:

Here's a simple solution:

find . -type f -iname "*.ipynb" | sed 's/\.ipynb$//1'


回答3:

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 {} \;


回答4:

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.



回答5:

Perl One Liner
what you want
find . | perl -a -F/ -lne 'print $F[-1] if /.*.ipynb/g'

Then not your code
what you do not want
find . | perl -a -F/ -lne 'print $F[-1] if !/.*.ipynb/g'

NOTE
In Perl you need to put extra .. So your pattern would be .*.ipynb



回答6:

If there's no occurrence of this ".ipynb" string on any file name other than a suffix, then you can try this simpler way using tr:

find . -type f -iname "*.ipynb" -print | tr -d ".ipbyn"


回答7:

If you don't know that the extension is or there are multiple you could use this:

find . -type f -exec basename {} \;|perl -pe 's/(.*)\..*$/$1/;s{^.*/}{}'

and for a list of files with no duplicates (originally differing in path or extension)

find . -type f -exec basename {} \;|perl -pe 's/(.*)\..*$/$1/;s{^.*/}{}'|sort|uniq