Project

General

Profile

1 3772 aaronmk
#!/bin/bash
2 3771 aaronmk
# Expands bash-style {} expressions.
3
# See <http://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion>.
4
# Filters each line from stdin to stdout.
5
# Warning: Due to shell limitations, a blank line will be interpreted as EOF.
6
7
sedEreFlag="$(test "$(uname)" = Darwin && echo E || echo r)"
8
9
sed () { "$(which sed)" -"$sedEreFlag" "$@";}
10
11
echoEach () { local line; for line in "$@"; do echo "$line"; done; }
12
13 3772 aaronmk
singleQuote="'"
14
singleQuoteEsc="'\''"
15
CR=$'\r'
16
LF=$'\n'
17 3773 aaronmk
braceKeep='./{'
18
bracketKeep='{*[*,*]*}'
19 3771 aaronmk
20
while true; do
21 3772 aaronmk
    read # get next line from stdin; strips trailing newlines
22
    line="$REPLY"
23 3771 aaronmk
    test -z "$line" && break # EOF if no line or empty line
24 3772 aaronmk
25 3773 aaronmk
    if test "${line/$braceKeep/}" != "$line" \
26
-o "${line/$bracketKeep/}" != "$line"; then # line contains unparseable exprs
27
        echo "$line" # don't expand
28
    else
29
        line="${line//$CR/}" # remove \r
30
        line="${line//$singleQuote/$singleQuoteEsc}" # escape single quotes
31
        line="$(echo "$line"|sed -e "s/[^{,}]+/'&'/g")" # escape non-brace chars
32
33
        eval echoEach $line # brace-expand $line
34
    fi
35 3771 aaronmk
done