【发布时间】:2018-04-12 23:48:56
【问题描述】:
我有以下漂亮的小 bash 函数可以在我的历史记录中进行搜索(例如,查找 ls 命令):
history | grep --color=always ls | sort -k2 | uniq -f 1 | sort -n
我将它打包成一个 bash 脚本,链接到一个别名 (histg),效果很好:
#!/bin/bash
if [ "$1" == "-h" ]; then
echo "A bash script to find patterns in history, avoiding duplicates (also non consecutive)"
echo "expands to: XX"
exit 0
fi
HISTSIZE=100000 # need this, because does not read .bashrc so does not know how big a HISTSIZE
HISTFILE=~/.bash_history # Or wherever you bash history file lives
set -o history # enable history
OUTPUT="$(history | grep --color=always $1 | sort -k2 | uniq -f 1 | sort -n)"
echo "${OUTPUT}"
通常,我会得到这种输出:
$ histg SI
16424 git commit -m "working on SI"
16671 git commit -m "updated SI"
17782 cd SI/
但是我想再做一项改进,但我不知道如何进行。我希望能够再次快速调用这些命令,但正如您所见,我的历史很大,所以输入 !17782 有点长。例如,如果我的历史记录的当前大小为 17785(我的最大历史记录大小为 100000),我想看看:
$ histg SI
16424 -1361 git commit -m "working on SI"
16671 -1114 git commit -m "updated SI"
17782 -3 cd ~/Desktop/crrt/wrk/SI/
这样我就可以输入-3
知道如何调整我的 bash 命令来添加此列吗?
【问题讨论】:
-
计算历史记录中的行数(17785),在每个匹配的行上迭代,减去行号(17782),用
-(-3)取反,将其添加到输出? -
类似的东西。我知道如何获取历史记录的行数(history | wc -l),然后开始努力工作。如何以可靠的方式(使用空格填充)插入计算结果(field_1 - wc_value)?
-
例如,您可以使用
printf "%10s" "$string"填充。man 3 printf -
如何使用
tac(cat的倒数)并添加一行,以及一个额外的tac。 (效率不高,但简单) -
我不确定这会是什么样子。你有这个案例的
tac示例吗?