Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

Bash use match regex with lookbehind pattern on string

bash --version

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin19)

Description:

I want to extract the WorkingDir key value from this string dictionary:

config="""
"TerraformCommand": "terragrunt-info",
  "WorkingDir": "usr/terraform-modules/terraform-aws-codebuild/examples/.terragrunt-cache/xh9X2WgTwVjjRHiPBjKUl0Lr86w/SGN8gG45haGoXT7IhOh9_iuKkbc"
}
"""

In this case, the expected output would be:

"usr/terraform-modules/terraform-aws-codebuild/examples/.terragrunt-cache/xh9X2WgTwVjjRHiPBjKUl0Lr86w/SGN8gG45haGoXT7IhOh9_iuKkbc"

Attempts:

So far I've tried using different methods using this positive lookbehind/lookahead pattern: '(?<=("WorkingDir":s")).+(?=")' 1.

echo `expr "$config" : '(?<=("WorkingDir":s")).+(?=")'`

Output: 0

2.

pat='(?<=("WorkingDir":s")).+(?=")'
[[ $config =~ $pat ]]
echo "${BASH_REMATCH[0]}"
echo "${BASH_REMATCH[1]}"

output:


echo $config | grep -o '(?<=("WorkingDir":s")).+(?=")'

output:

question from:https://stackoverflow.com/questions/65855862/bash-use-match-regex-with-lookbehind-pattern-on-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As was pointed out in the comments, expr only uses "basic" (aka "obsolete") regular expressions, and the regex engine that bash's =~ operator uses doesn't support lookahead or lookbehind (or the s shorthand for space either). But you don't need lookaround, just match everything and use a capture group to pick out the part you want (and store the pattern in a variable to avoid possible parsing inconsistencies):

WorkingDirPattern='"WorkingDir":[[:space:]]"([^"]+)"'
if [[ "$config" =~ $WorkingDirPattern ]]; then
    WorkingDir="${BASH_REMATCH[1]}"    # get the contents of the first capture group
    echo "WorkingDir is $WorkingDir"
else
    echo "No WorkingDir found" >&2
fi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...