4

Emacs 26.1

I have this text:

"ADA-SGD"
"ADT-SGD"
"ADX-SGD"
"AID-SGD"
"AMP-SGD"
"ANT-SGD"
"ARDR-SGD"
"ARK-SGD"

I want to swap text in all these lines. The result must be like this:

"SGD-ADA"
"SGD-ADT"
"SGD-ADX"
"SGD-AID"
"SGD-AMP"
"SGD-ANT"
"SGD-ARDR"
"SGD-ARK"

How I can do this?

Thanks.

Heikki
  • 3,066
  • 12
  • 19
a_subscriber
  • 4,062
  • 1
  • 18
  • 56

5 Answers5

6

I personally think the query-replace-regexp solution is better, but just for fun here is another solution with macros:

;; Move cursor to start of first line
<f3>      ;; kmacro-start-macro-or-insert-counter
M-f       ;; forward-word
M-t       ;; transpose-words
C-n       ;; next-line
C-a       ;; move-beginning-of-line
<f4>      ;; kmacro-end-or-call-macro
;; Select remaining lines
C-x C-k r ;; apply-macro-to-region-lines
0x5453
  • 329
  • 1
  • 7
  • Executing your macro with numeric argument 0 should also work as intended, as going past the last line in a buffer errors out and terminates execution. –  Jan 11 '19 at 21:26
5

You can do it with C-M-% (running query-replace-regexp): Give it the string "\([A-Z]+\)-\([A-Z]+\)" (quotes included) for the text to replace, and "\2-\1" for the replacement.

Harald Hanche-Olsen
  • 2,441
  • 13
  • 15
4

Another option: using Multiple Cursors you can do it with three commands!

Starting with point (the cursor) on the first hyphen -:

  1. Mark the hyphen with Shift right-arrow or C-space C-f
  2. Mark all hyphens with M-x mc/mark-all-like-this or C-c C-<
  3. Transpose words with M-x transpose-words or M-t
Tyler
  • 22,234
  • 1
  • 54
  • 94
3

You can simply use query-replace-regexp (default key C-M-%) for this. search pattern would be something like

"\(.*\)-\(SGD\)"

and the replacement would look like this then

"\2-\1"

replace-regexp is great for such things, check the emacs wiki for mor information about that emacs regexp

3

Regexps are an overkill in this case since emacs has a built-in command transpose-words that is bound to M-t by default. This command, combined with isearch are enough to solve the problem when linked together with emacs keyboard macros.

https://www.gnu.org/software/emacs/manual/html_node/emacs/Basic-Keyboard-Macro.html

Learn to use keyboard macros and you can solve most repetative text editing tasks.

Place the cursor before the first line, start recording the keyboard macro, press C-s and - to move the cursor to the next hyphen, press M-t to transpose the words, stop recording. Then repeat the macro as many times as needed. Alternatively, you can apply the macro to a region of lines.

Heikki
  • 3,066
  • 12
  • 19