Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

linux - Using 'find' to return filenames without extension

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To return only filenames without the extension, try:

find . -type f -iname "*.ipynb" -execdir sh -c 'printf "%s
" "${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
" "${@%.*}"' _ {} +

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
" "${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 ';'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...