Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capitalize strings in sed or awk

Tags:

bash

sed

awk

I have three types of strings that I'd like to capitalize in a bash script. I figured sed/awk would be my best bet, but I'm not sure. What's the best way given the following requirements?

  1. single word
    e.g. taco -> Taco

  2. multiple words separated by hyphens
    e.g. my-fish-tacos -> My-Fish-Tacos

  3. multiple words separated by underscores
    e.g. my_fish_tacos -> My_Fish_Tacos

like image 695
GregB Avatar asked Aug 03 '12 21:08

GregB


3 Answers

There's no need to use capture groups (although & is a one in a way):

echo "taco my-fish-tacos my_fish_tacos" | sed 's/[^ _-]*/\u&/g'

The output:

Taco My-Fish-Tacos My_Fish_Tacos

The escaped lower case "u" capitalizes the next character in the matched sub-string.

like image 168
Dennis Williamson Avatar answered Nov 11 '22 00:11

Dennis Williamson


Using awk:

echo 'test' | awk '{
     for ( i=1; i <= NF; i++) {
         sub(".", substr(toupper($i), 1,1) , $i);
         print $i;
         # or
         # print substr(toupper($i), 1,1) substr($i, 2);
     }
}'
like image 34
Sergii Stotskyi Avatar answered Nov 10 '22 23:11

Sergii Stotskyi


Try the following:

sed 's/\([a-z]\)\([a-z]*\)/\U\1\L\2/g'

It works for me using GNU sed, but I don't think BSD sed supports \U and \L.

like image 6
Andrew Clark Avatar answered Nov 11 '22 00:11

Andrew Clark