w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
How to match part of a string to a regex in bash?

The regex ^CGI$ only matches when the entire string is CGI. If you want to match any substring, use simply CGI.

This is because in a regular expression, ^ only matches at the beginning of a string ("anchors" to the beginning), and $ only at the end. That said, it's more conventional to use shell-style patterns here (with the = operator rather than =~), and simply use wildcards to disable their implicit anchoring.

Finally, since you want to look up through a variable lookup, you need to use variable indirection. So:

if [[ ${!varname} = *CGI* ]]; then
  echo "There is a CGI in the name"

That said, the better way to do it would be to use an array. So:

files=( CGInoimport doCGIimport donoCGInoimport importCGIno )
for file in "${files[@]}"; do
  [[ $file = *CGI* ]] && echo "There is CGI in the name $file"

...or, if the keys can be non-numeric or discontiguous, an associative array:

declare -A files=(
for key in "${!files[@]}"; do
  [[ ${files[file$key]} = *CGI* ]] && echo "There is CGI in $key"

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.