简体   繁体   中英

Bash script not taking regex pattern

This is my first time using bash and I want to develop a small script where, when the text file is provided as an argument, it reads the file line by line and in each line searches for words that match a certain regex pattern. If a word in a line matches the regex pattern I want the program to print the word.

shown below is my code:

#!/bin/bash
pat = "[((?:[a-z][a-zA-Z0-9_]*))(\\.)(png)]"
while IFS='' read -r line || [[ -n $line ]];do
   echo "Text read from file: $line"
   if [[ $line =~ $pat ]];
   then
        echo "line '$line'"
   else
        echo "DOES NOT MATCH BRANCH_REGEX"
   fi
done < $1

when I run this, the script says that:

test2.sh: 2: test2.sh: pat: not found Text read from file: # {{ parameters.application_name }} Performance Test Results test2.sh: 5: test2.sh: [[: not found DOES NOT MATCH BRANCH_REGEX

I cannot identify why the script is not taking the pattern

Your regex is not valid for bash. bash doesn't support non-capture group and double escaping dot is also a problem. Moreover you have space around = that is a syntax error. You should check your script on shellcheck.net for all syntax issues.

You just need to use this regex:

pat='[a-z][a-zA-Z0-9_]*\.png'

修复您的var声明(删除空格):

pat="[((?:[a-z][a-zA-Z0-9_]*))(\\.)(png)]"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM