Home > Net >  Replace first character of file in folder from Uppercase to Lower case
Replace first character of file in folder from Uppercase to Lower case

Time:06-26

I'm trying to convert 3,000 or so .svg files from CapitalCase to camelCase.

Current:

-Folder
--FileName1
--FileName2
--FileName3

Goal:

-Folder
--fileName1
--fileName2
--fileName3

How can I use terminal to change the casing on the first character with to lowercase?

Currently I've been trying something along these lines: for f in *.svg; do mv -v "$f" "${f:1}"; done

All files in the folder start with a letter or number.

CodePudding user response:

If you need to rename only the files of a folder, but not the files of its subfolders, then the following AsObjC script will do it.

The advantage of this code is that you don't have to worry about localization and special letters, which are problematic in shell commands.

use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

set theFolder to (choose folder) as text -- hfs path here

tell application "System Events"
    repeat with aFile in (get files of folder theFolder)
        set aName to name of aFile
        set firstCharcterNSString to (current application's NSString's stringWithString:(aName's character 1))
        set firstCharcter to firstCharcterNSString's lowercaseString() as text
        try
            set name of aFile to firstCharcter & (text 2 thru -1 of aName)
        on error
            set name of aFile to firstCharcter
        end try
    end repeat
end tell

CodePudding user response:

Solving in bash, tested and working fine, be careful though with your files you working on.

Renaming files in current directory where this script is, it's do lower-casing of the first letter, if it was uppercase, and yet nothing if it was a number, argument must be provided:

# 1 argument - folder name
# 2 argument - file extension (.txt, .svg, etc.)
for filename in $(ls "$1" | grep "$2")
do
  firstChar=${filename:0:1}
  restChars=${filename:1}
  if [[ "$firstChar" =~ [A-Z] ]] && ! [[ "$firstChar" =~ [a-z] ]]; then
    toLowerFirstChar=$(echo $firstChar | awk '{print tolower($0)}')
    modifiedFilename="$toLowerFirstChar$restChars"
    mv "$1/$filename" "$1/$modifiedFilename"
  else
    echo "Non-alphabetic or already lowercase"
    # here may do what you want fith files started with numbers in name
  fi
done

Use: bash script.sh Folder .txt

ATTENTION: Now here after running script and renaming, names of some files may coincide and there would be a conflict in this case. Can later fix it and update this script.

  • Related