下面的代码接受stdin ,过滤方法作为"$1"的宏,输出转到stdout 。
你可以使用它,例如,如下:
#Produce basic output, dynamically filter it in the terminal,
#and output the final, confirmed results to stdout
vi `find . | terminalFilter`
默认过滤宏是grep -F "$pattern"脚本提供模式变量作为当前输入的内容。 作为当前输入的函数的立即结果显示在终端上。 按 ,结果将成为最终结果并输出到stdout 。
#!/usr/bin/env bash
##terminalFilter
del=`printf "\x7f"` #backspace character
input="`cat`" #create initial set from all input
#take the filter macro from the first argument or use
# 'grep -F "$pattern"'
filter=${1:-'grep -F "$pattern"'}
pattern= #what's inputted by the keyboard at any given time
printSelected(){
echo "$input" | eval "$filter"
}
printScreen(){
clear
printSelected
#Print search pattern at the bottom of the screen
tput cup $(tput lines); echo -n "PATTERN: $pattern"
} >/dev/tty
#^only the confirmed results go `stdout`, this goes to the terminal only
printScreen
#read from the terminal as `cat` has already consumed the `stdin`
exec 0
while IFS=$'\n' read -s -n1 key; do
case "$key" in
"$del") pattern="${pattern%?}";; #backspace deletes the last character
"") break;; #enter breaks the loop
*) pattern="$pattern$key";; #everything else gets appended
#to the pattern string
esac
printScreen
done
clear
printSelected