01/05/2025

Shell : uppercase all files in directory

today twas easier to ask Gemini this time than search google. This script was generated by GEMINI 2.0 FLASH, after two prompts. I have to say it's just what I needed

first prompt : shellscript to uppercase filename (not extension)

#!/bin/bash

# Check if a filename is provided as an argument
if [ -z "$1" ]; then
  echo "Usage: $0 <filename>"
  exit 1
fi

filename="$1"
base="${filename%.*}"   # Extract the filename without the extension
extension="${filename#*.}" # Extract the extension

# Uppercase the base filename
uppercase_base=$(echo "$base" | tr '[:lower:]' '[:upper:]')

# Construct the new filename
if [ -z "$extension" ]; then
  new_filename="$uppercase_base" # No extension
else
  new_filename="${uppercase_base}.${extension}"
fi

# Rename the file
mv "$filename" "$new_filename"

echo "Renamed '$filename' to '$new_filename'"

second prompt : all folder files. I didn't bother to go further but you could certainly ask to use first script within a second script that does the loop. Well here is all in one script :

#!/bin/bash

# Loop through all files in the current directory
for file in *; do
  # Skip directories
  if [ -f "$file" ]; then
    filename="$file"
    base="${filename%.*}"
    extension="${filename#*.}"

    uppercase_base=$(echo "$base" | tr '[:lower:]' '[:upper:]')

    if [ -z "$extension" ]; then
      new_filename="$uppercase_base"
    else
      new_filename="${uppercase_base}.${extension}"
    fi

    # Only rename if the filename has changed
    if [ "$filename" != "$new_filename" ]; then
      mv "$filename" "$new_filename"
      echo "Renamed '$filename' to '$new_filename'"
    fi
  fi
done

echo "Finished processing files in the current directory."
To top