dav*_*vid 3 linux shell grep bash ssh
我machineB
在这个目录下有几个日志文件,/opt/ptd/Logs/
如下所示 - 我的日志文件非常大。
david@machineB:/opt/ptd/Logs$ ls -lt
-rw-r--r-- 1 david david 49651720 Oct 11 16:23 ptd.log
-rw-r--r-- 1 david david 104857728 Oct 10 07:55 ptd.log.1
-rw-r--r-- 1 david david 104857726 Oct 10 07:50 ptd.log.2
Run Code Online (Sandbox Code Playgroud)
我正在尝试编写一个通用的 shell 脚本,它应该尝试解析我的所有日志文件以machineB
获得特定模式并打印具有这些模式的行。我将运行我下面的 shell 脚本,machineA
从中设置了所有 ssh 密钥,这意味着我需要从 machineA 远程 grep 在 machineB 上的日志文件上。
#!/bin/bash
wordsToInclude="hello,animal,atttribute,metadata"
wordsToExclude="timeout,runner"
# now grep on the various log file for above words and print out the lines accordingly
Run Code Online (Sandbox Code Playgroud)
意思是,我将在wordsToInclude
变量中用逗号分隔单词- 如果我的日志包含hello
单词,则打印出该行,同时打印出包含animal
单词的行。与attribute
和metadata
词类似。
而且我将在wordsToExclude
变量中用逗号分隔单词- 如果任何行包含这些单词,则不要打印出这些行。
我现在使用上述格式来存储单词,但任何更好的格式对我来说都很好。我可以在wordsToInclude
和wordsToExclude
变量中有很长的单词列表,所以这就是我将它们存储在这些变量中的原因。
我知道如何对一小组变量进行 grep。如果我需要直接在 machineB 上从命令行执行 grep,那么我会这样做 -
grep -E 'hello|animal|atttribute|metadata' ptd.log | grep -v 'timeout'
Run Code Online (Sandbox Code Playgroud)
但是我不确定如何将它结合到我的 shell 脚本中,以便我可以从 machineA 在 machineB 上执行远程 ssh grep。
如果您对其他格式持开放态度,请考虑:
inc="hello|animal|atttribute|metadata"
exc="timeout|runner"
ssh machineB "grep -E '$inc' path/ptd.log | grep -vE '$exc'"
Run Code Online (Sandbox Code Playgroud)
如果您的日志文件很大并且您正在搜索固定词,而不是花哨的正则表达式,您可能需要考虑这种方法:
inc='hello
animal
atttribute
metadata'
exc='timeout
runner'
ssh office "grep -F '$inc' ptd.log | grep -vF '$exc'"
Run Code Online (Sandbox Code Playgroud)
通过将每个单词放在单独的行上,我们可以将 grep 的-F
功能用于固定字符串。这会关闭正则表达式处理,从而加快处理速度。
归档时间: |
|
查看次数: |
31632 次 |
最近记录: |