How to re-order pipe-delimited columns in Notepad++?

8

I am trying to reposition every line in a .txt file in the following way below. However I have no idea on how to go about it. Is this possible with Notepad++?

From
apple|apple123@aol.com|orange
celery|celery@aol.com|cabbage
sandwich|sandwich@aol.com|turkey

To
apple|orange|apple123@aol.com
celery|cabbage|celery@aol.com
sandwich|turkey|sandwich@aol.com

Lucyfer

Posted 2015-08-03T00:57:44.777

Reputation: 209

I just found this, which I didn't even know before but looks super useful: Edit columns in Notepad++ with TextFX plugin

– MC10 – 2015-08-03T01:12:28.217

I would not call this "repositioning lines". – Lightness Races with Monica – 2015-08-03T12:46:52.660

Answers

15

Re-ordering Columns in a Text File

Yes this is possible within vanilla Notepad++, though as noted there are also plugins that will do it. A better (more robust) approach might be to use some command-line text-processing tools, but if you need a quick-and-dirty solution you can find that below:

Assuming your exact input (col1|col2|col3, pipe delimeter, no pipe in col2):

Find: (.*?)\|(.*?)\|(.*)

Replace: \1|\3|\2

works for me here in Notepad++, built Jan 2015. Somewhat brutish, but it works.

Explanation:

.* - matches any character (except newline), between zero and unlimited times

.*? - matches any character (except newline) as above, in a non-greedy manner (ie match as little as possible)

(.*) - plain brackets denote capturing group of above (to use in Replace as eg \1, \2, \3 etc )

\| - \ escapes pipe (|) to match it literally

\1|\3|\2 - print 1st matching group, pipe, third matching group, pipe, second matching group

bertieb

Posted 2015-08-03T00:57:44.777

Reputation: 6 181

My pleasure, I'm glad it helped you and hope it will help others :-) It isn't necessary, but you can also click the tick mark to accept an answer if it solves your problem- you are free not to, or to wait for additional better answers too! – bertieb – 2015-08-03T01:24:03.383

Don't you need to make the .* non-greedy, I.e. .*? to avoid a lot of backtracking? – Ex Umbris – 2015-08-03T05:25:50.117

@ExUmbris: usually the optimization starts when the speed seems inadequate – nperson325681 – 2015-08-03T09:52:10.550

OTOH deliberately writing a suboptimal query for the sake of not writing a ? character seems silly. – Lightness Races with Monica – 2015-08-03T12:48:06.550

Adding a ? causes the query to fail with the test data, which is why I omitted it. – bertieb – 2015-08-03T13:23:34.373

1(.*?)|(.*?)|(.*) works for me. – Shaz – 2015-08-03T14:17:30.910

@Ryan could swear I tried that and had it not work originally; but it does (of course) so I have updated the answer and explanation to match. Thanks for you input! – bertieb – 2015-08-03T14:21:41.877