合并两个Bash历史文件

4
假设我有两个bash历史记录文件,如下所示: history1.txt:
    1  ls
    2  cd foo
...
  921  history > history1.txt

history2.txt:

  154  vim /etc/nginx/nginx.conf
  155  service nginx restart
...
 1153  history > history2.txt

我知道我可以很容易地编写一个bash脚本来合并这两个文件,使得结果文件包含1到1153行的历史记录条目而不重复... 就像下面的bash脚本一样:

merge.sh

HEAD=`head -n 1 history2.txt | sed -e 's/^[[:space:]]*//'`
sed -n -e "1,/$HEAD/p" history1.txt > merged.txt
sed -e "1,$ s/$HEAD//" -e '/^\s*$/d' history2.txt >> merged.txt

但我花费了比我愿意承认的更多时间,尝试仅使用无名管道、sed 或任何其他常见的 Linux 工具而不使用变量和命令替换(`command`)来完成这个任务。但是我没有成功 :(

有没有 Linux shell 大牛或 sed 大师知道这是否可能?

注意:我知道 merge.sh 脚本不能处理所有边缘情况。

4个回答

3
如果我理解正确的话,您只有两个没有重复项的文件(尽管不确定)。
所以您这里不需要使用sed或其他工具。只需要执行以下操作:
cat history1.txt history2.txt | sort -n > output

如果您有重复项:

cat history1.txt history2.txt | sort -n -u > output

谢谢,这正是我想要的,完全避免了使用sed,并且在两个历史记录根本没有重叠的情况下更加防护。 - MikeCompSciGeek

2

如果我理解正确,您想要将条目添加到您的历史文件中?您考虑使用内置的history -r吗?

$ cat foo
echo "history"
$ history | tail -n 5
 1371  rm foo
 1372  tail .bash_history > foo
 1373  vim foo 
 1374  cat foo
 1375  history | tail
$ history -r foo
$ history | tail -n 5
 1374  cat foo
 1375  history | tail
 1376  history -r foo
 1377  echo "history"
 1378  history | tail

也许你可以查看一下$ help history,以便找到符合你需求的内容。

历史记录 -r 或任何内置选项都与我的问题无关。 - MikeCompSciGeek

1

你必须学会使用正确的工具来解决UNIX中的问题,因为有很多看起来可以解决特定问题的错误方法,但实际上是缓慢、危险、不可移植、易碎等等。

sed仅用于对单个行进行简单的替换。shell用于操作文件和进程,并对UNIX工具进行调用排序。对于通用文本处理,标准的UNIX工具是awk。

由于您没有提供我们可以运行工具测试的示例输入/输出,因此以下内容未经过测试,但将非常接近正确:

awk '
NR==FNR {file1[$1]=$0;next}
{
    for (i=(prev+1); i<$1; i++) {
        print file1[i]
    }
    print
    prev = $1
}
' history1.txt history2.txt

0
如果您像这样创建文件:

  1  ls
  2  cd foo
  921  history > history1.txt

  154  vim /etc/nginx/nginx.conf
  155  service nginx restart
  1153  history >> history1.txt

现在所有的历史记录都在一个文件中。

使用cut命令选择只有命令行并剪切掉行号,例如:(-d用于按空格分割,-f用于从第4列选择到结尾)

cut -d " " -f 4- histroy1.txt > temp.txt

现在你可以在temp.txt文件中找到所有命令。 如果你使用sort和uniqe来整理

sort temp.txt |uniq

你可以将两个历史文件中使用过的所有独特命令放入一个文件中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接