Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upper- to lower-case using sed

Tags:

I'd like to change the following patterns:

getFoo_Bar 

to:

getFoo_bar 

(note the lower b)

Knowing neither foo nor bar, what is the replacement pattern?

I started writing

sed 's/\(get[A-Z][A-Za-z0-9]*_\)\([A-Z]\)/\1 

but I'm stuck: I want to write "\2 lower case", how do I do that?

Maybe sed is not adapted?

like image 249
cadrian Avatar asked Mar 27 '09 11:03

cadrian


People also ask

How do you change uppercase to lowercase in Linux?

The `tr` command can be used in the following way to convert any string from uppercase to lowercase. You can use `tr` command in the following way also to convert any string from lowercase to uppercase.

How do you use sed on a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

Can you change the text from lower case to upper case?

To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.


2 Answers

To change getFoo_Bar to getFoo_bar using sed :

echo "getFoo_Bar" | sed 's/^\(.\{7\}\)\(.\)\(.*\)$/\1\l\2\3/' 

The upper and lowercase letters are handled by :

  • \U Makes all text to the right uppercase.
  • \u makes only the first character to the right uppercase.
  • \L Makes all text to the right lowercase.
  • \l Makes only the first character to the right lower case. (Note its a lowercase letter L)

The example is just one method for pattern matching, just based on modifying a single chunk of text. Using the example, getFoo_BAr transforms to getFoo_bAr, note the A was not altered.

like image 185
Matt Thomas Avatar answered Sep 30 '22 16:09

Matt Thomas


s/\(get[A-Z][A-Za-z0-9]*_\)\([A-Z]\)/\1\L\2/g 

Test:

$ echo 'getFoo_Bar' | sed -e 's/\(get[A-Z][A-Za-z0-9]*_\)\([A-Z]\)/\1\L\2/g' getFoo_bar 
like image 36
strager Avatar answered Sep 30 '22 16:09

strager