Serious Shell Programming
  • Introduction
  • Acknowledgements
  • Basics
    • Strings
      • Single-Quotes
      • Double-Quotes
      • Unquoted Strings
      • Compound Strings
    • Here Documents
      • Here Doc
      • Indented Here Doc
      • Literal Here Doc
      • In-Memory Here Doc
    • Conditionals
      • Built-in test
      • Parameter Conditionals
      • Parameter test
    • Regex
      • grep
      • awk
      • pcre
    • Control Flow
      • Binary Operators
      • if-elif-else
      • case Statement
      • for Loop
      • while Loop
      • Functions
  • shellcheck
    • Introduction
    • Bad Advice
  • Style
    • awk
    • case
    • Redirection
    • Comments
    • trap
  • String Functions
    • substr
    • sprintf
    • replace
    • replaceall
    • replacestart
    • replaceend
    • fnmatch
  • awk
    • Pre-declaring Arrays
    • Sorting Arrays
  • Know Your limits
    • Arguments
    • Environment Variables
    • Solutions
Powered by GitBook
On this page

Was this helpful?

  1. awk

Sorting Arrays

#
# Like GNU awk's asort() but works with any awk(1)
# NB: Named _asort() to prevent conflict with GNU awk
#
function _asort(src, dest)
{
        k = nitems = 0
        for (i in src) dest[++nitems] = src[i]
        for (i = 1; i <= nitems; k = i++) {
                val = dest[i]
                while ((k > 0) && (dest[k] > val)) {
                        dest[k+1] = dest[k]; k--
                }
                dest[k+1] = val
        }
        return nitems
}

# Sample _asort() usage:
############################################################
#
#    string = "abc,123"
#    split(string, array, /,/)
#    n = _asort(array, sorted_array)
#    sorted_string = ""
#    for (i = 1; i <= n; i++)
#        sorted_string = sorted_string "," sorted_array[i]
#    sub(/^,/, "", sorted_string)
#    print sorted_string # produces "123,abc"
#
############################################################

#
# Like GNU awk's asorti() but works with any awk(1)
# NB: Named _asorti() to prevent conflict with GNU awk
#
function _asorti(src, dest)
{
        k = nitems = 0
        for (i in src) dest[++nitems] = i
        for (i = 1; i <= nitems; k = i++) {
                idx = dest[i]
                while ((k > 0) && (dest[k] > idx)) {
                        dest[k+1] = dest[k]; k--
                }
                dest[k+1] = idx
        }
        return nitems
}

# Sample _asorti() usage:
############################################################
#
#    foo["abc"] = 1 # value ignored
#    foo["123"] = 1 # value ignored
#    n = _asorti(foo, sorted_indices)
#    for (i = 1; i <= n; i++)
#        print sorted_indices[i]
#    # Output Produced:
#    #       123
#    #       abc
#
############################################################
PreviousPre-declaring ArraysNextArguments

Last updated 5 years ago

Was this helpful?