Sorting Data In a Line From Smallest To Largest



  • Hi,

    Im trying to figure out how to sort data in a line from smallest to largest. e.g:

    20 13 6 23 1 43

    Using the Line Operations in Lexicographically ascending order or integer ascending order doesnt seem to work. I would like to get the numbers to show as:

    1 6 13 20 23 43

    I am only asking because I have thousands of lines like this and cant seem to find a solution.

    Any help would greatly be appreciated



  • @Enrico-Cottee, welcome to the Notepad++ Community. You said:

    Using the Line Operations in Lexicographically ascending order or integer ascending order doesnt seem to work

    That’s because the operation is for sorting multiple lines in ascending order, not for sorting the tokens in one line in ascending order.

    I have thousands of lines like this

    If you had a single line, it would be easy, because you could use regex to replace spaces with newlines, then sort those lines, then replace newlines with spaces. But with multiple lines, it would be harder.

    Your best bet is going to be a programming language. You can do it externally to Notepad++, or using one of the scripting plugins that has direct access to the built-in editor (PythonScript, LuaScript, or jN Notepad++ – which give Python, Lua, or JavaScript access to the NPP internals). The basic algorithm will be: grab a line; split the line into tokens using space as separator; sort that list of tokens; join that list with spaces; replace the input line with the output line.



  • @PeterJones said:

    PythonScript… basic algorithm…

    Yep, it works.

    # encoding=utf-8
    """in response to https://notepad-plus-plus.org/community/topic/17743/"""
    from Npp import *
    
    def forum_post17743_FunctionName():
        """
        split each line into tokens; sort those tokens; replace the existing line
        """
        #console.show()
        #console.clear()
    
        # sort within each line of numeric tokens
        editor1.beginUndoAction()
        for lnum in range(editor1.getLineCount()):
            editor1.gotoLine(lnum)
            txt = editor1.getCurLine().rstrip()
            vals = sorted([int(x) for x in txt.split()])
            repl = " ".join([str(x) for x in vals])
            #console.write("[{}] => [{}]\n".format(txt, repl))
            editor1.replaceLine(lnum, repl)
        editor1.endUndoAction()
    
    if __name__ == '__main__': forum_post17743_FunctionName()
    

    (And yes, @Alan-Kilborn, I am addicted.)



  • I just noticed I forgot to change back from editor1.xxx to editor.xxx: for my debugging, I was editing the script in editor2, so wanted to make sure it would run on my test file in editor1 every time… but for actually usage, you should use editor, so it always checks the active editor pane, whichever it is.


Log in to reply