andrew
andrew

Reputation: 89

AWK command to convert one of the column of text file to Camelcase String

I have to convert all the column values to camelCase letters/String

Text.1

PriId,testId,status,timestamp
007,1,ABC,20198743874398
006,2,pqr,43546346456565
005,3,test data, 7697439567904586

Output:-
PriId,testId,status,timestamp
007,1,Abc,20198743874398
006,2,Pqr,43546346456565
005,3,Test Data,5654675477765

Upvotes: 0

Views: 550

Answers (3)

Ed Morton
Ed Morton

Reputation: 203502

$ cat tst.awk
NR>1 {
    rec = ""
    while ( match($0,/[[:alpha:]]+/) ) {
        rec = rec substr($0,1,RSTART-1) \
                  toupper(substr($0,RSTART,1)) \
                  tolower(substr($0,RSTART+1,RLENGTH-1))
        $0 = substr($0,RSTART+RLENGTH)
    }
    $0 = rec $0
}
{ print }

$ awk -f tst.awk file
PriId,testId,status,timestamp
007,1,Abc,20198743874398
006,2,Pqr,43546346456565
005,3,Test Data, 7697439567904586

Note: as WalterA said, this is not camelCase but looks like your example data.

Upvotes: 1

Walter A
Walter A

Reputation: 20002

Skip the first line and force Upper and Lowercase with

sed -r '2,$s/(\w)(\w*)/\U\1\L\2/g' file

Note: This is not camelCase but looks like your example data.

Upvotes: 2

Jotne
Jotne

Reputation: 41456

This gnu awk (due to splitting by null string) may do.

awk -F, -v OFS="," '
NR>1{
    $3=tolower($3);n=split($3,a,"");f=1;
    for (i=1;i<=n;i++) {
        if (a[i-1]==" " || f) {
            a[i]=toupper(a[i]);f=0} 
        s=s a[i]}
    $3=s;s=""}
1' file
PriId,testId,status,timestamp
007,1,Abc,20198743874398
006,2,Pqr,43546346456565
005,3,Test Data, 7697439567904586

And in one line

awk -F, -v OFS="," 'NR>1{$3=tolower($3);n=split($3,a,"");f=1;for (i=1;i<=n;i++) {if (a[i-1]==" " || f) {a[i]=toupper(a[i]);f=0};s=s a[i]};$3=s;s=""}1' file

How it works:

awk -F, -v OFS="," '            # Set input and output Field Separator to ,
NR>1{                           # Skip first line
    $3=tolower($3);             # Change filed 3 to all lower character
    n=split($3,a,"");           # Split filed 3 to array a and number of characters in n
    f=1;                        # Set flag f to true (detect start of word)
    for (i=1;i<=n;i++) {        # Going trough one and one characters 
        if (a[i-1]==" " || f) { # If previous field is space or flag f is true (first characer)
            a[i]=toupper(a[i]); # Set character to upper case
            f=0}                # Clear flag f, since its not first field any more
        s=s a[i]}               # Join together filed 3 in variable s
    $3=s;s=""}                  # Set filed 3 to s and clear s
1' file                         # 1 gives print the line

Upvotes: 2

Related Questions