LearnToGrow
LearnToGrow

Reputation: 1750

Search and convert to lower case in Vim

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:

Upvotes: 6

Views: 3622

Answers (4)

sidyll
sidyll

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

Randeep Singh
Randeep Singh

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

Ingo Karkat
Ingo Karkat

Reputation: 172540

You basically just need two things:

  • Capture groups :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).
  • The :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:

  • I've established a keyword start assertion (\<) 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

stack0114106
stack0114106

Reputation: 8711

In the command mode try this

:1,$ s/object.attribute/self.lowercase(attribute)/g

Upvotes: -1

Related Questions