How can I get the list of only filenames and remove directory and subdirectories using find, sed, awk, cut or any.

For e.g : I get list of all media files using find as such:

find /var/warehouse/* -type f \( -name "*.avi" -o -name "*.mkv" -o -name "*.flv" -o -name "*.mp4" \) -exec ls {} +


/var/warehouse/movies/Blade/The Lion King (1994).mkv
/var/warehouse/movies/Blade/The Secret [Dual Audio] Upscaled 720p Ripped by FÅM€.mkv
/var/warehouse/movies/Bollywood/Bhaag Milkha Bhaag - DVDScr - XviD - 1CDRip - [DDR].avi

I wanted output as:

The Lion King (1994).mkv
The Secret [Dual Audio] Upscaled 720p Ripped by FÅM€.mkv
Bhaag Milkha Bhaag - DVDScr - XviD - 1CDRip - [DDR].avi


find /var/warehouse/* -type f \( -name "*.avi" -o -name "*.mkv" \
    -o -name "*.flv" \
    -o -name "*.mp4" \) \
    -exec basename {} \;

or you can combine find with sed:

find /var/warehouse/* -type f \( -name "*.avi" -o -name "*.mkv" \
    -o -name "*.flv" \
    -o -name "*.mp4" \) | sed -e 's!.*/!!'
  • Your perl example will fail on his files with whitespace/globs. – llua Oct 29 '14 at 18:41
  • @arx: Remove that and replace with a sed. – cuonglm Oct 30 '14 at 2:55
  • @cuonglm : can u explain how sed syntax works here – amolveer Oct 30 '14 at 7:25
  • @amolveer: .*/ matches all thing until the last /, then we remove it. ! is used as delimiter in sed subsitution command, s!!!. – cuonglm Oct 30 '14 at 7:30

You have most of it already. You just need to change your -exec to a -printf

find /var/warehouse/* -type f \( -name "*.avi" -o -name "*.mkv" -o -name "*.flv" -o -name "*.mp4" \) -printf "%f\n"

%f will print the name of the file that was found, ignoring the path to it.

You may also want to consider changing your -name to -iname (case insensitive match) so that it matches files like *.Avi and *.AVI as well.

  • -printf is not defined by POSIX, it only work at least in GNU find. – cuonglm Oct 29 '14 at 14:50
  • it does not work for the directories inside warehouse since those directories also get listed with the base filename Output returned as : Blade/The.Bucket.List[2007]DvDrip-aXXo.avi Blade/The Lion King (1994).mkv Blade/The.Pursuit.of.Happyness.2006.DVD5.720p.BluRay.x264-REVEiLLE.en.mkv Blade/The Secret [Dual Audio] Upscaled 720p Ripped by FÅM€.mkv Blade/Yes.Man.2008.DvDRip-FxM.avi Bollywood/Bhaag Milkha Bhaag - DVDScr - XviD - 1CDRip - [DDR].avi while I need list of only base filenames. – amolveer Oct 29 '14 at 15:17
  • 1
    @amolveer You're right, that's my mistake. Should be %f instead of %P. – Omnipresence Oct 29 '14 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.