Home > Enterprise >  Replacing patterns with grep and regex
Replacing patterns with grep and regex

Time:11-27

I was wondering if with grep and regex we can do something in the spirit of the following example:

Original text:

name_1_extratext
name_2_extratext

Target:

name_extratext_1
name_extratext_2

I am particularly interested in doing this within Vim. Thanks

CodePudding user response:

grep doesn't "do" anything to what it matches; it only matches.

Use sed:

echo "name_1_extratext" | sed -E 's/_([^_] )_(.*)/_\2_\1/'

CodePudding user response:

@bohemian's comment about grep only doing matching also applies within Vim. "grep" and "regex" are not, or should not, be vague buzzwords you throw at a problem. They are tools that may or may not be adapted to the class of problem you are having and a large part of learning is acquiring the correct intuition for what tool to use in what case.

In Vim, what you want to do is a substitution. It doesn't involve grep at all but it definitely involves regular expressions.

In this specific case, you would do something like this:

:%s/\(.*\)\(_\d\ \)\(.*\)/\1\3\2

or this variant of @bohemian's answer:

:%s/_\([^_]\ \)_\(.*\)/_\2_\1/

or anything that works and makes sense to you, really. Ideally not something you copy/pasted from the internet but something you really understand.

Reference:

  • The :s command is introduced in chapter 10 of the user manual: :help 10.2, and further documented under :help :s.
  • The % range is also introduced chapter 10 of the user manual: :help 10.3, and further documented under :help :range.
  • Vim's own regular expression dialect is extensively documented under :help pattern.
  • Related