cadrian
cadrian

Reputation: 7376

upper- to lower-case using sed

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?

Upvotes: 25

Views: 40442

Answers (7)

Dušan
Dušan

Reputation: 59

Shortest I can come up with:

echo getFoo_Bar | sed 's/_./\L&/'

Upvotes: 5

user2923416
user2923416

Reputation: 1

If you want to write everything in lowercase just after underscore, than this would work for you:

echo getFoo_Bar | gawk -F_ '{print tolower($2)}'

Upvotes: 0

zer0cool
zer0cool

Reputation: 1

echo getFoo_Bar | sed 's/[Bb]/\L&/g'

Upvotes: -2

Matt Thomas
Matt Thomas

Reputation: 1465

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.

Upvotes: 41

kalyanji
kalyanji

Reputation: 4918

Somewhat shorter:

echo getFoo_Bar | sed 's/_\(.\)/_\L\1/'

Upvotes: 8

brian-brazil
brian-brazil

Reputation: 34122

You can use perl for this one:

perl -pe 's/(get[A-Z][A-Za-z0-9]*)_([A-Z])/\1_\l\2/'

The \l is the trick here.

sed doesn't do upper/lowercase on matched groups.

Upvotes: 3

strager
strager

Reputation: 90012

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

Upvotes: 26

Related Questions