Skip to main content
4 of 4
added 258 characters in body
Kusalananda
  • 356.1k
  • 42
  • 737
  • 1.1k

Your code does not include any arrays. Also, it puts a list of filenames into a string, $file_list. The contents of the string will end with file3.png and your parameter substitution removes .png from the string, leaving you with a single string of filenames where the last filename does not have a filename suffix.

Putting multiple separate objects (pathnames) into a single string automatically disqualifies the script from working properly for files whose names contains spaces (or whatever delimiter the string uses). Using an array would not help as you would still split the output of find on whitespaces.


To trim the extension off of all filenames of regular files in or below the current directory:

find . -type f -name "*.*" -exec sh -c ' for pathname do printf "Would move %s to %s...\n" "$pathname" "${pathname%.*}" # mv -i "$pathname" "${pathname%.*}" done' sh {} + 

This looks for regular files whose names contains at least one dot. The pathnames of these files are fed in batches into a small shell script that loops over them. The shell script renames the files by removing the last dot in the filename and everything that comes after. The actual mv command is commented out for safety.

The find command acts as a generator of pathnames for the internal shell script, and we are guaranteed to properly process pathnames containing spaces, newlines and tabs. There is no need for storing the output of commands in variables.

If you have an array of pathnames, possibly created by using

shopt -s globstar nullglob file_list=( **/*.* ) # get pathnames of files with dots in their names 

Then you would be able to output the pathnames without suffixes with

printf '%s\n' "${file_list[@]%.*}" 

Whether this would help you, I don't know. If you want to use the pathnames with no suffixes for something, then using the output of the above printf command would be the wrong thing to do (you would be back at not handling strange pathname again). So when and how you delete the filename suffixes depends on what you'd like to do with the result.

Related:

Kusalananda
  • 356.1k
  • 42
  • 737
  • 1.1k