gran_profaci
gran_profaci

Reputation: 8463

Remove underscore and capitalize character after it

I was just wondering if there is a way to replace every underscore in every file in a folder (say .java files) and convert the next character to uppercase, like

And what if we had id and we wanted to capitalize both I and D, as in

I haven't tried anything yet since I'm still learning. Can I do something like s/_/\U\1/g in sed or can I use some script to do this?

Upvotes: 9

Views: 3259

Answers (4)

Håkon Hægland
Håkon Hægland

Reputation: 40718

You can try the following bash script:

#! /bin/bash
files=(*.java)
for ((i=0; i<=${#files[@]}; i++ )) ; do
    file="${files[$i]}"
    awk -f r.awk "$file" > "${file}.mod"
done

where r.awk is

{
    str=$0
    mstr=""
    while(match(str,/_([[:alnum:]])/,a)) {
        q=substr(str,RSTART+RLENGTH,2)
        chr=a[1]
        pos=RSTART+RLENGTH
        pos2=RSTART-1
        if (length(q)==1) {
            if (match(q,/[[:alnum:]]/)) {
                chr=chr q
                pos=pos+1
            }
        }
        else if (length(q)==2) {
            if (match(q,/[[:alnum:]][[:blank:]]/)) {
                pos=pos+1
                chr=chr substr(q,1,1)
            }
        }
        mstr=(mstr substr(str,1,pos2) toupper(chr))
        str=substr(str,pos)
    }
    print (mstr str)
}

Given input file file1.java

getEmployee_Name getEmployee_Name
us_employee_id
    us_employee_id
asdf_asdf__

we get from awk -f r.awk file1.java :

getEmployeeName getEmployeeName
usEmployeeID
    usEmployeeID
asdfAsdf__

Upvotes: 0

anubhava
anubhava

Reputation: 784878

Little more verbose from awk but it will work on all gnu/non-gnu Unix flavors:

> s='get_employee_Name'
> awk -F _ '{printf "%s", $1; for(i=2; i<=NF; i++) printf "%s", toupper(substr($i,1,1)) substr($i, 2); print"";}' <<< "$s"
getEmployeeName

Upvotes: 2

Barmar
Barmar

Reputation: 780655

Perl script:

use String::CamelCase qw(camelize);

while (<>) {
  print camelize($_);
}

Upvotes: 1

Joseph Quinsey
Joseph Quinsey

Reputation: 9952

Your suggestion 's/_/\U\1/g' is very close. If you have the GNU sed, then the following should work:

sed 's/_\(.\)/\U\1/g'

(I say should, because what you wish for is not always what you want.)

Upvotes: 10

Related Questions