awk

Compare wildcard string inside bash awk command


Is there a way to compare a substring with wildcard in bash inside “awk” command like this

awk '{for(i=1;i<=NF;i++) if ($i=="redis-*") print $(i+1)}' /etc/redis/sentinel.conf | head -1 I want the command to look for any string that starts with “redis-” e.g., redis-pers, redis-test, redis-session etc from the sentinel.conf file.

I do not want to grep the string (e.g., redis-test), but the string that following the wildcard. So if the sentinel.conf file has a line like tis sentinel known-slave redis-test 192.168.1.100 6379 , i want to return 192.168.1.100


Solution

  • Awk doesn't have the glob (wildcard) syntax you're looking for, but you can convert your pattern to a regular expression and match that using the ~ operator:

    if ($i ~ /^redis-/)
    

    Regular expressions are more capable than shell globs - any glob pattern can be expressed as a regexp (but not vice versa).