0

I have a JS file with about 1,000 variables that looks like this:

export const FruitOrange: React.FC = () => (
    <Trans id="fruit.orange">Orange</Trans>
);
export const FruitApple: React.FC = () => (
    <Trans id="fruit.apple">Apple</Trans>
);

I want to sort all the variables in this to be in alphabetical order.

In other words, I want to sort the variable declarations so that FruitApple comes before FruitOrange.

How can I do this?

I just need to reformat the file once; any tool that can do this automatically is acceptable; I just don't want to hand-sort 1,000 variables.

Patrick Kenny
  • 4,515
  • 7
  • 47
  • 76
  • 1
    Small note: having c.1000 components doesn't seem like a very cost-effective method to do a translation service. – Andy Apr 02 '23 at 09:10
  • I've not tried this so I'll add it as a comment. I would write a macro that put all the lines for an export on a single line, copy and paste 1000 lines into Excel, sort in Excel, paste it back into Intellij and reformat the code. – matt helliwell Apr 02 '23 at 09:42

2 Answers2

1

Use MS Word for example

Copy and paste your code in.

  • Control H, search for ^p (the trailing space is important, so you only capture the indented lines) and 'Replace All' them with nothing.

  • Control H, search for ^p} and 'Replace All' them with }.

  • Now each definition is on a single line. In the Home icon-bar thingy, go to the Paragraph section and press Sort (the A->Z icon).

Then copy-paste it back into your code editor, such as VS Code, and get it to reformat.

This should work as long as any multi-line definitions have indentation (which again, VS Code and others should do for you).

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
1
  1. Make all the variables single line with regex(.* toggle) replacer (ctrl+h)
    \n(?!export) -> <<NEWLINE>>
export const FruitOrange: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.orange">Orange</Trans> <<NEWLINE>>);
export const FruitApple: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.apple">Apple</Trans> <<NEWLINE>>);
  1. Select all text(ctrl-a) and use VSCode command Sort Lines Ascending from the command pane (ctrl-shift-p)
export const FruitApple: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.apple">Apple</Trans> <<NEWLINE>>);
export const FruitOrange: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.orange">Orange</Trans> <<NEWLINE>>);
  1. Restore your newlines back
    <<NEWLINE>> -> \n
export const FruitApple: React.FC = () => (
    <Trans id="fruit.apple">Apple</Trans>
);
export const FruitOrange: React.FC = () => (
    <Trans id="fruit.orange">Orange</Trans>
);
Dimava
  • 7,654
  • 1
  • 9
  • 24