Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Correct Syntax For Escaping Double Quotes in Regex Pattern Match?

I’m trying to get the 2nd substring between the double quotes chars in vars string & string2.

I think the problem is the way I’m trying to escape the double quotes.

What is the correct syntax for this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/bash

# Example strings.

string='"name": "Bash scripting cheatsheet",'
string2='"url": "https://devhints.io/bash"'

# I'm trying to get the 2nd substring between " "

# desired matches:
# string_name_match='Bash scripting cheatsheet'
# string2_url_match='https://devhints.io/bash'

# Attempts: using a pattern var with double quotes escaped.

pattern='\".*\"'  # Is the " char escaped correctly?
echo "$string" | awk "/$pattern/{print $2}" # Is the $pattern var used correctly?
echo "$string2" | awk "/$pattern/{print $2}" 

# 2nd pattern match using the name/url to parse:

name_pattern='^\"name:\"[:space:].*[^\",]'
url_pattern='^\"url\"[:space:]\"^url:.*[^"]'
echo "$string" | awk "/$name_pattern/{print $0}"
echo "$string2" | awk "/$url_pattern/{print $0}"

>Solution :

Here is how you do it in awk:

awk -F '"' -v n=2 '{print $(n*2)}' <<< "$string"
Bash scripting cheatsheet

awk -F '"' -v n=2 '{print $(n*2)}' <<< "$string2"
https://devhints.io/bash
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading