Convert camelCase to Underscores Using sed

This short post deals with converting strings of the form camelCase or CamelCase into camel_case, and vice versa. These are three different popular naming conventions for variable/function/class names.

Convert CamelCase or camelCase to camel_case:

1
sed -e 's/\([A-Z]\)/_\l\1/g' -e 's/^_\([a-z]\)/\1/g' file.txt

Convert camel_case to camelCase

1
sed -e 's/_\([a-z]\)/\u\1/g' file.txt

Convert camel_case to CamelCase:

1
sed -e 's/_\([a-z]\)/\u\1/g' -e 's/^\([a-z]\)/\u\1/g' file.txt

If you enjoyed this post, make sure you subscribe to my RSS feed!

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

No related posts.

Tags: ,

Saturday, May 30th, 2009 Bash

5 Comments to Convert camelCase to Underscores Using sed

  • Michael says:

    Thanks for sharing this Amir.

    Would it be possible to carry out the following in one script or command?

    camelCase => camel_case
    camelCaseLong => camel_case_long
    camelCaseXYZ => camel_case_xyz

    CamelCase => Camel_Case
    CamelCaseLong => Camel_Case_Long
    CamelCaseXYZ => Camel_Case_XYZ

    I’m open to all suggestions.

    Many thanks,

    Michael

  • Amir Watad says:

    This does half of the job:

    1
    sed -e 's/\([a-z]\)\([A-Z]\)/\1_\2/g' -e 's/^_\([a-zA-Z]\)/\1/g' file.txt

    Will try to find a complete solution as soon as I have time.

  • Michael says:

    I look forward to a full solution.

    Thanks again Amir.

  • Manish Sinha says:

    AFAIK

    TcpListener– this is PascalCase
    tcpListener — this is camelCase

  • Oran says:

    Another solution to convert camel_case to CamelCase:
    sed -e ‘s/\(^\|_\)\(.\)/\U\2/g’

  • Leave a Reply

    my email
    my photo
    Hi,
    My name is Amir Watad. I have a BSc. in biomedical engineering from The Biomedical Engineering school , Technion , Israel, and a BSc. in electrical engineering from The Electrical Engineering school , Technion , Israel.
    I'm a Verification Engineer in Mellanox Technologies Ltd.
    I love Linux, the Command Line and the OpenSource Community.
    I used to write Poems (Arabic) when I was able to find time for this.
    May 2009
    S M T W T F S
    « Mar   Jun »
     12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31  
    SEO Powered by Platinum SEO from Techblissonline

    Twitter links powered by Tweet This v1.7.4, a WordPress plugin for Twitter.