Explanation of command to uppercase the first letter of a filename

Solution 1:

for i in *; 
    do new=`echo "$i" | sed -e 's/^./\U&/'`;
    mv "$i" "$new";
done;

Would be the entire code broken down to make it easily viewable, I'll explain below.


First we have to make sure we process every file, the following line means: "Do the following as long as you can find files"

for i in *;

Then we have to load the current filname (which is stored in variable $i), replace the first letter by a capitalized version and store the new name (in variable $new).

The following command basically means: Make variable $new (do new=) Load $i and forward it ("$i" |) to a function that replaces the first letter by a capitalized one. (sed -e 's/^./\U&/';`)

The sed manual page can be found here. It's used to perform basic text transformations. What is basically does is use a regular expression (the 's/^./\U&/' part) (a way of detecting a certain pattern in a text) to detect first-characters that are uncapitalized and replace it with a capitalized version.

do new=echo "$i" | sed -e 's/^./\U&/';

After we've gotten the new name, it's time to rename the file with it's new capitalized name, the following command does that.

It says: move (same as rename) the old file foo.bar to the new Foo.bar.

mv "$i" "$new";

So we now have one file renamed and it's time to move to the next. The following concludes the for function, telling it it is now time to move on and process the next file.

done;

Solution 2:

Here are a couple of other techniques in case your sed doesn't support \U:

for i in *; do first=$(echo "${i:0:1}" | tr '[:lower:]' '[:upper:]'); new=$first${i:1}; mv "$i" "$new"; done

If you have Bash 4:

for i in *; do mv "$i" "${i^}"; done

Solution 3:

Welcome to Bash, where just about everything is possible if not immediately obvious.

BloodPhilia explanation is very good for your specific request. If you are interested, here are some additional web resources to learn more:

Bash:

Sed (which is the 'S'tream 'ED'itor):

  • Gentle Intro: sed one-liners explained
  • The definitive tutorial: Bruce Barnett
  • definitive guide: GNU Sed Reference Manual

Solution 4:

To capitalize each first character in filename with BASH you can use a following construct: file_words=( $file ) echo "${file_words[@]^}"

It's much clearer than using sed and you only use BASH, so it's faster.