Check the link is correct (URL)

I read this other question , which has a really good regular expression to work with, but as far as I can see, they do not work with BASH commands as BASH commands do not support such complex rexegs.

if echo "http://www.google.com/test/link.php" | grep -q '(https?|ftp|file)://[-A-Z0-9\+&@#/%?=~_|!:,.;]*[-A-Z0-9\+&@#/%=~_|]'; then echo "Link valid" else echo "Link not valid" fi 

But this does not work, since grep -q does not work ...

Edit , I only realized that grep has an extended regular expression (-E) option that seems to make it work. But if someone has a better / faster way, I will still love here.

+6
url bash validation hyperlink
source share
2 answers

The following work is done in Bash> = version 3.2 without using grep :

 regex='(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]' string='http://www.google.com/test/link.php' if [[ $string =~ $regex ]] then echo "Link valid" else echo "Link not valid" fi 

Your regular expression does not seem to contain lowercase letters [az] , so I added them here.

+15
source share

Perhaps because the regular expression is written in PCRE syntax. See if you have (or can install) the pcregrep program on your system β€” it has the same syntax as grep , but accepts Perl-compatible regular expressions β€” and you should be able to do this.

Another option is to try the -P version of grep , but the manual page says that it is "very experimental", so it may or may not work.

I will say that you should carefully consider whether it is really advisable to use this or any regular expression to validate the URL. If you want to have the correct check, you probably would be better off finding or writing a small script, such as Perl, to use the tools for checking the language url.

EDIT . In response to your editing in the question, I did not notice that this regular expression also acts in the syntax "advanced". I don’t think you can get better / faster.

+1
source share

All Articles