我最近编写了一个bash脚本来检查文件中是否存在特定段落。 文件的内容是。
发布1EO的 保存完成
贸易节约为贸易节省成功 56945458 | 220841 | b for MCR:CMDTY from source:ICE Tradecapture API 重试次数:0(从这一行我们检查公司名称 - CMDTY)发布4EO的 保存完成
贸易节约为贸易节省成功 5666688 | 000 | b for MCR:CMDTY from source:ICE发布1EO的 保存完成
贸易节约为贸易节省成功 56945458 | 220841 | b for MCR:CMDTY from source:ICE Tradecapture API 重试次数:0(从这一行我们检查公司名称 - CMDTY)
需要匹配的段落是。
发布1EO的 保存完成
贸易节约为贸易节省成功 56945458 | 220841 | b for MCR:CMDTY from source:ICE Tradecapture API 重试次数:0(从这一行我们检查公司名称 - CMDTY)
将上段内容保存在名为temp。
的文件中我写了一个简单的脚本来完成这个任务,但似乎没有以某种方式工作。
#!/bin/bash
result=$(cat temp | grep -A 2 "Published 1EO's")
echo $result
line="Published 1EO's Save completed Trade saving save successful for trade 56945458|220841|b for MCR: CMDTY from source:ICE Tradecapture API retry count: 0 (From this line we check Company Name – CMDTY)"
echo $line | grep "\b$result\b"
if [ "$line" == "$result" ]; then
echo "match"
else
echo "does not match"
fi
任何帮助将不胜感激。
谢谢。
答案 0 :(得分:1)
通常,这些不一样。 grep var $ result,里面包含新行(\ n)字符,而$行包含空格。
如果在echo $ result之前设置IFS = $“\ n”,您将能够看到它们之间的区别。
我必须在$ line(在正确的位置)插入一些\ n,现在工作正常:
#!/bin/bash
result=$(cat test.log | grep -A 2 "Published 1EO's")
IFS=$"\n"
echo $result
line=$(echo -e "Published 1EO's\nSave completed\nTrade saving save successful for trade 56945458|220841|b for MCR: CMDTY from source:ICE Tradecapture API retry count: 0 (From this line we check Company Name – CMDTY)")
echo "----------------------------------"
#echo $line | grep "\b$result\b"
echo $line
unset IFS
if [[ $line = $result ]]; then
echo "match"
else
echo "does not match"
fi
结果:
$./bashtest.sh
Published 1EO's
Save completed
Trade savi g save successful for trade 56945458|220841|b for MCR: CMDTY from source:ICE Tradecapture API retry cou t: 0 (From this li e we check Compa y Name – CMDTY)
----------------------------------
Published 1EO's
Save completed
Trade savi g save successful for trade 56945458|220841|b for MCR: CMDTY from source:ICE Tradecapture API retry cou t: 0 (From this li e we check Compa y Name – CMDTY)
match