basename not working as expected from find -exec

I have the following files in a directory

> ls -1 /tmp/test/dir/
file with spaces 1.ogg
file with spaces 2.ogg

I am running the following to echo the filenames but alter the file extension on the files to .mp3 instead of .ogg ( I am going to run ffmpeg against the files ultimately, but keeping the example simple for the sake of the thread).

find /tmp/test/ -type f -name "*.ogg" -exec echo {} "$(basename {} .ogg).mp3" \;

I expect the output to be:

/tmp/test/dir/file with spaces 2.ogg /tmp/test/dir/file with spaces 2.mp3
/tmp/test/dir/file with spaces 1.ogg /tmp/test/dir/file with spaces 1.mp3

But instead it fails to remove the .ogg and I end up with:

/tmp/test/dir/file with spaces 2.ogg /tmp/test/dir/file with spaces 2.ogg.mp3
/tmp/test/dir/file with spaces 1.ogg /tmp/test/dir/file with spaces 1.ogg.mp3
  • Note the ".ogg.mp3" extension *

A basic echo works as expected:

> echo $(basename /tmp/test/dir/file\ with\ spaces\ 1.ogg .ogg).mp3
file with spaces 1.mp3

I can only assume this has something to do with the space between {} and .ogg in the confines of find.

How can I run this so it produces the desired filename?

Hi, try:

find /tmp/test/ -type f -name "*.ogg" -exec sh -c 'echo "{} $(basename "{}" .ogg).mpg"' \;
1 Like

Thanks very much!

In the end I got it working as follows (using ffmpeg):

find ./ -type f -name "*.ogg" -exec sh -c 'ffmpeg -i "{}" "$(dirname "{}")/$(basename "{}" .ogg).mp3"' \;