aboutsummaryrefslogtreecommitdiffstats
path: root/tools/filter
blob: 0d27b9b9007e8054e5db30219fb595d0750bbc35 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/sh

set -e

if [ -z "$1" ]; then
    echo "Usage: $0 <command>"
    echo ""
    echo "Run the given test expression for each newline-separated line in stdin, and echo only the lines that return zero."
    echo "(Think filter in many programming languages)."
    echo 'The iterator variable is called "$ELEM", and the index variable is called "$IDX".'
    exit 1
fi

i=0
while IFS=$'\n' read -r line; do
    j=0
    for item in $line; do
        eval "X${j}='$item'"
        j=$((j+1))
    done

    set +e
    IDX=$i ELEM="$line" eval "test $1"
    if [ $? -eq 0 ]; then
        echo "$line"
    fi
    set -e
    i=$((i+1))
done