Jag*_*uri 7 linux bash shell ubuntu sh
我有兴趣在终端中键入搜索关键字,并能够看到输出immediately
和interactively
.这意味着,就像在Google中搜索一样,我希望在每个字符或单词键入后立即获得结果.
我想通过组合WATCH命令和FIND命令来做到这一点,但无法带来交互式.
让我们假设,为了在文件名中搜索名称为'hint'的文件,我使用该命令
$ find | grep -i hint
Run Code Online (Sandbox Code Playgroud)
这几乎给了我不错的输出结果.
但我想要的是交互式的相同行为,这意味着无需重新输入命令,只需键入SEARCH STRING.
我编写了一个shell脚本,它从STDIN读取并每1秒执行一次上面的PIPED-COMMAND.因此,我输入的内容每次都是指令的指令.但是WATCH命令不是交互式的.
我感兴趣的是以下类型的OUTPUT:
$ hi
./hi
./hindi
./hint
$ hint
./hint
Run Code Online (Sandbox Code Playgroud)
如果有人可以用任何更好的替代方式帮助我而不是我的PSUEDO代码,那也很好
偶然发现这个老问题,发现它很有趣,并认为我应该尝试一下。这个 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
Run Code Online (Sandbox Code Playgroud)
希望这能达到您的目的。我包含了一个“开始目录”选项,因为如果您搜索整个主文件夹或其他内容,列表可能会变得非常笨拙。$1
如果不需要的话就扔掉吧。使用其中的 ascii 值$n
应该可以轻松地包含一些热键功能,例如退出或保存结果。
编辑:
如果启动脚本,它将显示“开始输入...”并等待按键。如果搜索字符串足够长(由变量定义MINLEN
),则任何按键都会触发find
使用当前搜索字符串的运行(grep
这里似乎有点多余)。该脚本传递给 的任何参数find
。这可以提供更好的搜索结果和更短的结果列表。-type d
例如,将搜索限制为目录、-xdev
将搜索保留在当前文件系统等(请参阅 参考资料man find
)。退格键会将搜索字符串缩短一,而按 Escape 键将退出脚本。当前搜索字符串显示在顶部。我以前-iname
的搜索是不区分大小写的。将其更改为“-name”以获得区分大小写的行为。