关于使用 shell 脚本检索 Laravel 日志报错信息变量中包含特殊字符的问题

- 问题描述

逐行检索一个文件中的内容在另一文件中是否存在,不存在则输出

- 环境复现

两个日志文件:
test.log、test_new.log
一个脚本文件:
check.sh
准备文件
文件内容:
test.log文件中的内容:

local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)
local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)

test.log
test_new.log文件中的内容:

local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)
local.ERROR: Use of undefined constant hhh - assumed 'hhh' {exception:[object] (ErrorException(code: 0): Use of undefined constant hhh - assumed 'hhh' at /data/wwwroot/test/laravel55/routes/web.php:15)

test_new.log
chech.sh文件中的内容:

#!/bin/bash

bak=$IFS
IFS=$'\n'
for i in $(cat test_new.log); do
    if [ `grep '$i' test.log` ] ;then
      continue
    else
      echo $i
      break
    fi
done
IFS=$bak

check.sh

- 调试运行

预期:
输出 test_new.log 中第二行内容
实际:
输出 test_new.log 中第一行内容
运行结果

- 问题猜想

检索时由于一行变量中存在特殊字符导致检索失败

- 验证猜想

验证猜想

- 结论

由于变量中包含特殊含义的字符 ( $, *, [, |, ^, (, ), / )等,导致检索失败

- 提出问题

请问各路大神,这种变量中存在特殊字符的检索问题改如何破解?或者有没有更好的办法能满足我的需求?
小弟学浅,望不吝赐教!
:pray:

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案

关于你提出的主要问题,用 --fixed-string 即可解决(grep 默认认为你要检索的是一个模式字符串)。

另外其实不需要用 if [ ],直接 || 更简单些。如果你选择用 if,那么可以去掉 [ ],if 的本意即为检查程序的 Exit code。

#!/bin/bash

string_a="hell'o
worl[d"

string_b="hello
worl[d"

for l in $string_a; do
    echo "$string_b" | grep --fixed-string "$l" 2>&1 >/dev/null || echo "$l"
done
4年前 评论
Hello-world (楼主) 4年前
讨论数量: 2

关于你提出的主要问题,用 --fixed-string 即可解决(grep 默认认为你要检索的是一个模式字符串)。

另外其实不需要用 if [ ],直接 || 更简单些。如果你选择用 if,那么可以去掉 [ ],if 的本意即为检查程序的 Exit code。

#!/bin/bash

string_a="hell'o
worl[d"

string_b="hello
worl[d"

for l in $string_a; do
    echo "$string_b" | grep --fixed-string "$l" 2>&1 >/dev/null || echo "$l"
done
4年前 评论
Hello-world (楼主) 4年前

对了,能如此清晰地在提问时表达出「我想要什么」、「我遇到的问题」、「我是如何尝试的(复现)」、「我对目前遇到问题的猜想」的人不多了。加油。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!