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

How do i get the value present in first double quotes?

I’m currently writing a bash script to get the first value among the many comma separated strings.
I have a file that looks like this –

name


things: "water bottle","40","new phone cover",10



place

I just need to return the value in first double quotes.

water bottle

The value in first double quotes can be one word/two words. That is, water bottle can be sometimes replaced with pen.
I tried –

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

awk '/:/ {print $2}'

But this just gives

water

I wanted to comma separate it, but there’s colon(:) after things. So, I’m not sure how to separate it.
How do i get the value present in first double quotes?

EDIT:

SOLUTION:
I used the below code since I particularly wanted to use awk –

awk '/:/' test.txt | cut -d\" -f2

>Solution :

You can use sed:

sed -n 's/^[^"]*"\([^"]*\)".*/\1/p' file > outfile

See the online demo:

#!/bin/bash
s='name
 
 
things: "water bottle","40","new phone cover",10
 
 
 
place'
 
sed -n 's/^[^"]*"\([^"]*\)".*/\1/p' <<< "$s"
# => water bottle

The command means

  • -n – the option suppresses the default line output
  • ^[^"]*"\([^"]*\)".* – a POSIX BRE regex pattern that matches
    • ^ – start of string
    • [^"]* – zero or more chars other than "
    • " – a " char
    • \([^"]*\) – Group 1 (\1 refers to this value): any zero or more chars other than "
    • ".* – a " char and the rest of the string.
  • \1 replaces the match with Group 1 value
  • p – only prints the result of a successful substitution.
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