
Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In programming, there are different styles of variable naming, such as snake case, Pascal case, and others. Sometimes we may want to convert between them. For this purpose, we can use automated tools such as shell scripts.
In this tutorial, we’ll learn how to convert the snake case naming style to Pascal case in the shell.
Snake case is a naming convention where words are linked via underscore symbols. Each word consists of lowercase letters. For example, the variable this_is_the_string uses the snake case style.
On the other hand, Pascal case is a convention whereby words are linked together without separators, and each word starts with a capital letter. An example of Pascal case is ThisIsTheString.
Now, let’s look at how we can convert from snake case to Pascal case in Linux.
We can use the sed command with regular expressions (shortened as regex) to convert from snake case to Pascal case:
$ echo "this_is_the_string" | sed -r 's/(^|_)(.)/\U\2/g'
ThisIsTheString
We can see that the initial snake case string this_is_the_string has been converted to the Pascal case string ThisIsTheString.
Let’s take a closer look at the shell command we’re using:
Now, let’s analyze the regex pattern:
Notably, the \U pattern in regex is a GNU extension to POSIX, so it may not be available in non-GNU shells.
Overall, the command above converts the snake case string to the Pascal case string and prints its output to the shell.
Perl is a popular alternative to sed when working with regular expressions. The following command converts to Pascal case:
$ echo "this_is_the_string" | perl -pe 's/(?:^|_)./uc($&)/ge;s/_//g'
ThisIsTheString
Let’s look at its regex pattern:
Overall, the output of this command is similar to what we achieved in the previous example.
In case we don’t want to utilize any other tools, we can achieve the same goal by using a Bash shell one-liner:
$ uscore="this_is_the_string"; arr=(${uscore//_/ }); printf %s ${arr[@]^}
ThisIsTheString
So, let’s take a closer look at the command:
As a result, we can see that the snake case string is converted to Pascal case correctly.
In this article, we learned how to convert the snake case to the Pascal case in the shell.
Firstly, we looked at the sed command with regular expressions. Secondly, we utilized Perl as an alternative to sed. Finally, we looked at pure shell commands that can achieve the same goal.