Josh Friedlander
Josh Friedlander

Reputation: 11657

Capitalise a varying phrase in same position in Terminal

I have a number of .py files that contain a line like this:

self._cols = [self.foo.bar.relevant_string.str()]

I need to capitalise the relevant_string, to get this

self._cols = [self.foo.bar.RELEVANT_STRING.str()]

in all ~100 of them.

Is there a way to do this with bash/awk/perl? I tried something like this

perl  -pe 's/self.foo.bar./uc($&)/e' *.py

But it capitalised the captured area, not the part after.

Upvotes: 2

Views: 73

Answers (5)

user7712945
user7712945

Reputation:

use perl 5, or gnu sed

perl -i -pe 's/(self.foo.bar.)(\w+)/\1\U\2/g' *.py

identically just replace 'perl -i -pe' with

sed -i -E 

Upvotes: 0

stack0114106
stack0114106

Reputation: 8711

One more Perl, using look-behind

$ echo "self._cols = [self.foo.bar.relevant_string.str()]" |
    perl -pe 's/(?<=self.foo.bar.)(\w+)/uc($1)/ge'
self._cols = [self.foo.bar.RELEVANT_STRING.str()]
$

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133538

Could you please try following.

awk '
match($0,/self\.foo\.bar\.[^.]*/){
  print substr($0,1,RSTART+12) toupper(substr($0,RSTART+13,RLENGTH-13)) substr($0,RSTART+RLENGTH)
  next
}
1
'  Input_file

Output will be as follows.

self._cols = [self.foo.bar.RELEVANT_STRING.str()]

Upvotes: 1

Ed Morton
Ed Morton

Reputation: 203684

With GNU sed:

$ echo 'self._cols = [self.foo.bar.relevant_string.str()]' |
    sed -E 's/(self\.foo\.bar\.)([^.]+)/\1\U\2/'
self._cols = [self.foo.bar.RELEVANT_STRING.str()]

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You may use \K after your pattern to omit it from the match and match the part you need to change the case of using \w+ (that matches 1 or more letters, digits or underscores):

perl -i -pe 's/self\.schemata\.usage\.\K\w+/uc($&)/e' *.py

See the online demo:

s="self._cols = [self.schemata.usage.relevant_string.str()]"
perl -pe 's/self\.schemata\.usage\.\K\w+/uc($&)/e' <<< "$s"
# => self._cols = [self.schemata.usage.RELEVANT_STRING.str()]

Upvotes: 2

Related Questions