Skip to content

Instantly share code, notes, and snippets.

@emanuele6
Created May 31, 2022 00:29
Show Gist options
  • Save emanuele6/1d41604a8c233a95227c78d7f2b0a3b8 to your computer and use it in GitHub Desktop.
Save emanuele6/1d41604a8c233a95227c78d7f2b0a3b8 to your computer and use it in GitHub Desktop.

Revisions

  1. emanuele6 created this gist May 31, 2022.
    46 changes: 46 additions & 0 deletions bashrematch_stack.bash
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    #!/bin/bash --
    # https://lists.gnu.org/archive/html/bug-bash/2022-05/msg00052.html

    bashrematch_push () {
    local BASH_REMATCH a
    for a
    do [[ $a =~ .* ]]
    done
    }
    bashrematch_pop () {
    local i
    for (( i = (${1-1}); i; --i )); do
    printf '%s\n' "$BASH_REMATCH"
    unset -v BASH_REMATCH
    done
    }

    # Examples:
    # bash-5.1$ printf '%s\n' a b c | bashrematch_tac
    # c
    # b
    # a
    #
    # bash-5.1$ printf 'd\ne\nf\ng' | bashrematch_tac
    # gf
    # e
    # d
    bashrematch_tac () {
    local REPLY i=0
    while read -r; do
    bashrematch_push "$REPLY"
    (( ++i ))
    done
    printf '%s' "$REPLY"
    bashrematch_pop "$i"
    }

    # Examples:
    # bash-5.1$ a=( el1 el2 el3 ); bashrematch_reverse "${a[@]}"
    # el3
    # el2
    # el1
    bashrematch_reverse () {
    bashrematch_push "$@"
    bashrematch_pop "$#"
    }