Monday, April 15, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 3905  / 3 Years ago, wed, june 9, 2021, 11:13:52

I use the same regex with grep and it gives me a match but when doing it in a bash script, it return no match.



Test String(part of the file testregex.txt):



<a href="/os_x_lynx-wallpapers.html"><p>OS X Lynx</p><img src="/thumbs/os_x_lynx-t1.jpg"alt="OS X Lynx" class="thumb_img" width="270" height="169"/></a></div><div style="float:right;margin-right:13px;"></div></div>



This command correctly matches the highlighted part(and a few more):



grep -E '<img src="[^"]*.jpg"' testregex.txt


But this bash script returns no match:



page=$(<testregex.txt)

if [[ $page =~ '<img src="[^"]*.jpg"' ]]; then
echo $1
echo "match found"
else
echo "match not found!"
fi

More From » bash

 Answers
4

In the case =~ operator, just don't use quotes for the right operator. This is considered an extended regular expression so in this case the single quotes will be part from he regular expression. So, using single quotes, a string like '<img src="/thumbs/os_x_lynx-t1.jpg"' (which contain also single quotes around it) will be found. See Meaning of “=~” operator in shell script.



Also, you must to escape any special character in your regex (quotes, spaces, shell redirection - <):





#!/bin/bash
page=$(<testregex.txt)

if [[ $page =~ <img src="[^"]*.jpg" ]]; then
echo $1
echo "match found"
else
echo "match not found!"
fi





Apart of =~, you can use in your script your original command which uses grep:



#!/bin/bash

if grep -qE '<img src="[^"]*.jpg"' testregex.txt ; then
echo $1
echo "match found"
else
echo "match not found!"
fi


In this case I used -q option for grep to not write anything to standard output and to exit immediately if any match is found.


[#26221] Thursday, June 10, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brailloni

Total Points: 122
Total Questions: 108
Total Answers: 108

Location: North Korea
Member since Tue, Apr 4, 2023
1 Year ago
brailloni questions
Tue, Jun 21, 22, 21:51, 2 Years ago
Thu, Jul 29, 21, 05:25, 3 Years ago
Sat, Apr 2, 22, 17:32, 2 Years ago
Mon, Oct 31, 22, 21:39, 1 Year ago
;