Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping 2 columns with Emacs

Tags:

emacs

I have 2 columns, separated by comma. How can I swap those columns with Emacs?

I have the following:

  column 1,column2
  x1,x2
  y1,y2
  f1,f2

and I want it like this:

 column2,column 1
 x2,x1
 y2,y1
 f2,f1
like image 314
AKM Avatar asked Nov 22 '10 14:11

AKM


3 Answers

Use M-x query-replace-regexp and then:

\(.+\),\(.+\)

as replace regexp and

\2,\1

for replacement.


In Emacs, you need to escape grouping parentheses with \. So, above regexp would be usually written as

(.+),(.+)

which means that you want everything before comma in first group and everything after comma in second group.

\2,\1

means: write second group, then comma, then first group.

like image 122
darioo Avatar answered Oct 17 '22 08:10

darioo


While you can apply techniques given by other people, you can also use the org-mode tables. Once you convert the data into org-mode table, it is very easy to swap the columns by simple keystrokes. You can have M-x org-mode, select the region then do M-x org-table-convert-region, and then M- on the right most column. I am not sure, how to export the data as CSV, but that should be very easy for you with replace-regexp. This can be helpful: http://www.gnu.org/software/emacs/manual/html_node/org/Tables.html#Tables

like image 21
aartist Avatar answered Oct 17 '22 07:10

aartist


Similar to the answer given by @darioo, type the following into the top of your buffer:

(query-replace-regexp "\\(.*?\\),\\(.*\\)" "\\2,\\1")

Then, put your cursor at the end of this line and press ctrl-x, ctrl-e.

You will have an interactive search-and-replace for which you press the space bar to make the change, and press ctrl-g to quit. If you press ! (exclamation mark) then the search will cease being interactive and take place on all matching text.

If you want to reverse the changes then press M-x (usually ESC followed by x) and type undo and press enter.

like image 35
PP. Avatar answered Oct 17 '22 08:10

PP.