0

I need to search for a certain word, and if it occurs, move it to the end of the line where it occured. For instance, search for "bugs".

Welcome! Meta Stack Exchange is intended for bugs, features, and discussions

Turns into:

Welcome! Meta Stack Exchange is intended for, features, and discussions bugs

2
:g/ \?\<bugs\>/normal! dgn$p

Explanation:

:g/.../ for all lines matching a pattern

\?\<bugs\> an optional space followed by "bugs" (a whole word)

normal! dgn$p delete last match; go to end of line; put last match there

1

You can use a :substitute command for this:

:%s/\v ?(<bugs>)(.*)/\2 \1
  • :%s substitute
  • / start of regular expression
  • \v use very magic mode. This makes this regular expression a bit easier to read/write, because you don't need to use so many backslashes
  • [SPACE]? an optional space
  • (<bugs>) find the entire word bugs, and save it in capture group 1. The angle brackets <> mark the start and end of a word. The parentheses () mark the start and end of a capture group
  • (.*) find anything that follows, and save it in capture group 2
  • / end of regular expression
  • \2 \1 replace the matched text with the contents of capture group 2, followed by a space, followed by the contents of capture group 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.