Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize the first letter of every word in a filename or directory in Shell

Tags:

bash

shell

unix

I'm trying to write a shell command where I can specify a directory, and then every file and directory inside will have the first letter of every word capitalized. So

/doCumenTS/tesT.txt

should change to

/DoCumenTS/TesT.txt

I'm thinking it should start like

for i in directory do
tr something_goes_here
done

The problem I can't figure out is how to only do the first letter. I've made a script that uppercase the whole file name, but I can't figure out how to only get the first letter of every word.

Thanks!

like image 809
user1507982 Avatar asked Jul 06 '12 23:07

user1507982


People also ask

How do you capitalize the first letter in a shell script?

You can convert the case of the string more easily by using the new feature of Bash 4. '^' symbol is used to convert the first character of any string to uppercase and '^^' symbol is used to convert the whole string to the uppercase.

How do you auto capitalize the first letter of every word?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and then press fn+ SHIFT + F3 until the style you want is applied.

What is it called when you capitalize the first letter of every word?

CamelCase Words are written without spaces, and the first letter of each word is capitalized. Also called Upper Camel Case or Pascal Casing.

How do you capitalize every word in a string in word?

We can capitalize each word of a string by the help of split() and substring() methods. By the help of split("\\s") method, we can get all words in an array. To get the first character, we can use substring() or charAt() method.


2 Answers

Source="ONE TWO THREE FOUR"
Target="One Two Three Four"

Solution is below:

Target=`echo $Source | tr [A-Z] [a-z] | sed -e 's/^./\U&/g; s/ ./\U&/g'`
echo $Target

One Two Three Four

Taken from here: http://souravgulati.webs.com/apps/forums/topics/show/8584862-shell-script-capitalize-first-letter-of-every-word-of-a-line-

like image 200
Parvinder Singh Avatar answered Oct 11 '22 17:10

Parvinder Singh


Using GNU Sed

You can do this quite easily with GNU sed. For example:

$ echo '/doCumenTS/tesT.txt' | sed 's!/.!\U&!g'
/DoCumenTS/TesT.txt

Limitations

Note that the \U escape is a GNU sed extension. The manual says:

Finally, as a GNU 'sed' extension, you can include a special sequence made of a backslash and one of the letters 'L', 'l', 'U', 'u', or 'E'.

`\U'
     Turn the replacement to uppercase until a `\L' or `\E' is found
like image 35
Todd A. Jacobs Avatar answered Oct 11 '22 16:10

Todd A. Jacobs