我对在终端中键入搜索关键字感兴趣,并且能够看到输出immediately
和interactively
。这意味着,像在google中搜索一样,我希望在键入每个字符或单词后立即获得结果。
我通过结合WATCH命令和FIND命令来做到这一点,但是无法带来交互性。
假设,要在文件名中搜索名称为“hint”的文件,请使用以下命令
$ find | grep -i hint
这几乎给了我不错的输出结果。
但是我想要以交互方式实现相同的行为,这意味着无需重新键入命令,而只需键入SEARCH STRING。
我努力编写一个从STDIN读取并每1秒执行一次上述PIPED-COMMAND的shell脚本。因此,无论我键入什么内容,每次都将其作为指令使用。但是WATCH命令不是交互式的。
我对以下输出感兴趣:
$ hi
./hi
./hindi
./hint
$ hint
./hint
如果有人可以用其他更好的方法代替我的PSUEDO CODE来帮助我,那也很好
最佳答案
迷迷糊糊地想到了这个老问题,发现它很有趣,并认为我会尝试一下。这个BASH脚本为我工作:
#!/bin/bash
# Set MINLEN to the minimum number of characters needed to start the
# search.
MINLEN=2
clear
echo "Start typing (minimum $MINLEN characters)..."
# get one character without need for return
while read -n 1 -s i
do
# get ascii value of character to detect backspace
n=`echo -n $i|od -i -An|tr -d " "`
if (( $n == 127 )) # if character is a backspace...
then
if (( ${#in} > 0 )) # ...and search string is not empty
then
in=${in:0:${#in}-1} # shorten search string by one
# could use ${in:0:-1} for bash >= 4.2
fi
elif (( $n == 27 )) # if character is an escape...
then
exit 0 # ...then quit
else # if any other char was typed...
in=$in$i # add it to the search string
fi
clear
echo "Search: \""$in"\"" # show search string on top of screen
if (( ${#in} >= $MINLEN )) # if search string is long enough...
then
find "$@" -iname "*$in*" # ...call find, pass it any parameters given
fi
done
希望这能完成您打算做的事情。我包括了“开始目录”选项,因为如果您搜索整个主文件夹或其他内容,列表可能会变得很笨拙。如果不需要,只需转储
$1
。使用
$n
中的ascii值,也应该很容易包含一些热键功能,例如退出或保存结果。编辑:
如果启动脚本,它将显示“开始输入...”并等待按键被按下。如果搜索字符串足够长(由变量
MINLEN
定义),则任何按键操作都将触发使用当前搜索字符串运行的find
(此处grep
似乎有点多余)。该脚本会将给定的所有参数传递给find
。这样可以提供更好的搜索结果和更短的结果列表。例如,-type d
将搜索限制在目录中,-xdev
将搜索保留在当前文件系统等上(请参阅man find
)。退格键会将搜索字符串缩短一倍,而按Escape键将退出脚本。当前搜索字符串显示在顶部。我使用-iname
进行搜索,不区分大小写。将其更改为“-name”以区分大小写。