3

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.

3

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
| improve this answer | |
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.

| improve this answer | |
4

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
| improve this answer | |
  • 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. – user12563 Jan 11 '19 at 21:26
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

| improve this answer | |
2

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.

| improve this answer | |
  • See also @0x5453's answer, which likewise used transpose-words in a keyboard macro. – phils Jan 9 '19 at 21:02

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.