Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k 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:


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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...