简体   繁体   English

“ awk”未按预期处理shell变量

[英]“awk” is not processing shell variables as expected

I am working on filtering Specific text from a log file. 我正在从日志文件中过滤特定文本。 Problem here is that awk is not processing on shell variable. 这里的问题是awk没有在shell变量上处理。 But working fine on filename. 但是在文件名上工作正常。 I am storing a new log entry that comes in log file in a shell variable using "new_log=tail -n5 alerts.log" in a loop whenever a new log comes, then , 每当有新日志出现时,我都会在循环中使用“ new_log = tail -n5 alert.log”将新的日志条目存储在shell变量中的日志文件中,然后,

Level_no=`awk '{FS="Rule: "}{print $2}' "$new_log" | sed '/^$/d' | awk '{FS=" "}{print $3}' | sed 's/)//g'

Output: 输出:

awk: fatal: cannot open file `** Alert 1564460779.1380: mail  - ossec,syscheck
* New Log starts from ** Alert 1564460779.1380: mail  - ossec,syscheck *`

Above mentioned command works well when I run it in terminal using filename instead of shell variable as follows: 当我在终端使用文件名而不是shell变量在终端中运行它时,上述命令运行良好,如下所示:

awk '{FS="Rule: "}{print $2}' logs_mining | sed '/^$/d' | awk '{FS=" "}{print $3}' | sed 's/)//g'

But its performance issue if I store new log entry in another file and process from there. 但是如果我将新的日志条目存储在另一个文件中并从那里进行处理,则会出现性能问题。

So I researched more and more and came to know about awk variables...here is my shell script.. 因此,我进行了越来越多的研究,并了解了awk变量...这是我的shell脚本..

Level_no=`awk -v var="$new_log" '{FS="Rule: "}{print $2}' var | sed '/^$/d' | awk '{FS=" "}{print $3}' | sed 's/)//g'

Then output says 然后输出说

awk: fatal: cannot open file `var' for reading (No such file or directory)

Actual Result should be Successful execution of awk script. 实际结果应为成功执行awk脚本。

If new_log contains the data you want to process, not a filename, you need to pipe it to awk . 如果new_log包含要处理的数据而不是文件名,则需要将其通过管道传输到awk You can do this with a here-string. 您可以使用here字符串。

Level_no=`awk '{FS="Rule: "}{print $2}' <<<"$new_log" | sed '/^$/d' | awk '{FS=" "}{print $3}' | sed 's/)//g'`

It's also not necessary to pipe the output to sed and another awk , you can do it all in the first script. 也不必将输出传递给sed和另一个awk ,您可以在第一个脚本中完成所有操作。

Level_no=$(awk -F'Rule: ' '$2 != "" {split($2, a, " "); gsub(/)/, "", a[3]); print a[3]}' <<<"$new_log")

You probably don't need the variable, though, just pipe the output of the command to awk: 不过,您可能不需要该变量,只需将命令的输出通过管道传递给awk:

Level_no=$(tail -n5 alerts.log | awk -F'Rule: ' '$2 != "" {split($2, a, " "); gsub(/)/, "", a[3]); print a[3]}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM