Shell script to check if a paragraph/stream of lin

2019-03-05 16:08发布

I recently got to write a bash script to check if a perticular paragraph exist in a file. Content of the file is.

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)

Published 4EO's
Save completed
Trade saving save successful for trade 5666688|000|b for MCR: CMDTY from source:ICE

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)

the paragraph which needs to be matched is.

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)

saved the content of above paragraph in a file named temp.

I wrote a simple script to do this task, But It seems to be not working somehow.

#!/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

Any help will be appreciated.

Thank you.

标签: linux bash shell
1条回答
啃猪蹄的小仙女
2楼-- · 2019-03-05 16:23

Typically , these are not the same. The grep var $result, contains new line (\n) characters inside, while the $line contains spaces.

If you set IFS=$"\n" before echo $result, you will be able to see the difference between them.

I had to insert some \n to $line (in the correct position) and now works fine:

#!/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

Result:

$./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
查看更多
登录 后发表回答