首页 > 解决方案 > 重击。Grep 文本文件从其他文件中查找行

问题描述

是否可以分析文本文件让我们说log.txt从另一个文件中寻找行 - 让我们说config.txt. 我试图做以下事情:

while read -r line;
do
    if grep -q $line $log_path; then 
        echo "Found line: $line" >> $out_log
        break
    else echo "Line not found: $line" >> $out_log
    fi
done < $conf_path

$conf_path是一条像/path/to/config.txt

$log_path是一条像/path/to/log.txt

是用来测试脚本是否正常工作的$out_log/path/to/output_log.txt

例子$line"ERROR: MESSAGE: \[Library not found \!\]". 我在脚本之外测试了 grep 指令,它发现该行正确,所以我不认为 grep 是这里的问题。每次else执行语句。

谢谢你,社区,任何建议,

最好的问候, 马克斯

标签: bashshellgrep

解决方案


试试下面

代码:

while read -r line
do if grep -q "${line}" $log_path
then  echo "Found line: $line" >> $out_log
else echo "Line not found: $line" >> $out_log
fi
done < $conf_path

例子:

bash-3.2$ echo $conf_path ; cat $conf_path
config.txt
ERROR: MESSAGE: \[Library not found \!\]
ERROR: MESSAGE: \[File not found \!\]
ERROR: MESSAGE: \[Path not found \!\]
ERROR: MESSAGE: \[Permission denied \!\]
bash-3.2$ 
bash-3.2$ echo $log_path; cat $log_path
log.txt
INFO: MESSAGE: Script Starts
INFO: MESSAGE: Some command output
ERROR: MESSAGE: [Library not found !]
INFO: MESSAGE: Some other command output
ERROR: MESSAGE: [Path not found !]
INFO: MESSAGE: Exit script with 2
bash-3.2$ 
bash-3.2$ while read -r line; do if grep -q "${line}" $log_path; then  echo "Found line: $line" >> $out_log; else echo "Line not found: $line" >> $out_log; fi; done < $conf_path
bash-3.2$ 
bash-3.2$ echo $out_log; cat $out_log
output_log.txt
Found line: ERROR: MESSAGE: \[Library not found \!\]
Line not found: ERROR: MESSAGE: \[File not found \!\]
Found line: ERROR: MESSAGE: \[Path not found \!\]
Line not found: ERROR: MESSAGE: \[Permission denied \!\]
bash-3.2$ 

希望这可以帮助。祝你好运 !!


推荐阅读