Reputation: 1750
I have some textual file with source code that contains object.<attribute>
, where <attribute>
can be an array, for example object.SIZE_OF_IMAGE[0]
, or a simple string. I want to use a regular expression in Vim to find all occurrences of object.<attribute>
and replace them with self.<attribute_lowercase>
, in which <attribute_lowercase>
is the lowercase version of <attribute>
.
I can use :%s/object.*/self./gc
and perform the replacement manually, but it is very slow.
Here are some examples of the desired outcomes:
object.SIZE
becomes self.size
object.SIZE_OF_IMAGE[0]
becomes self.size_of_image[0]
Upvotes: 6
Views: 3622
Reputation: 59287
Based on your comment above that the attribute part "finishes by space or [ or (" you could match it with:
/object\.[^ [(]*
So, to replace it with self.attribute
use a capturing
group and \L
to make everything lowercase:
:%s/\vobject\.([^ [(]*)/self.\L\1/g
Upvotes: 0
Reputation: 101
sed -E 's/object\.([^ \(]*)(.*)/self.lowercase(\1)\2/g' file_name.txt
above command considers that your attribute is followed by space or "("
you can tweek this command based on your need
Upvotes: 1
Reputation: 172540
You basically just need two things:
:help /\(
let you store what's matched in between \(...\)
and then reference it (via \1
, \2
, etc.) in the replacement (or even afterwards in the pattern itself).:help s/\L
special replacement action that makes everything following lowercase.This gives you the following command:
:%substitute/\<object\.\(\w\+\)/self.\L\1/g
Notes:
\<
) at the beginning to avoid matching schlobject
as well.\w\+
matches letters, digits, and underscores (so it fulfills your example); various alternatives are possible here.Upvotes: 14
Reputation: 8711
In the command mode try this
:1,$ s/object.attribute/self.lowercase(attribute)/g
Upvotes: -1