Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract substring in the double quotes by using awk or other methods?

Tags:

linux

awk

I want to extract you in this sample string:

See [ "you" later 

However, my attempt does not work as expected:

 awk '{ sub(/.*\"/, ""); sub(/\".*/, ""); print }' <<< "See [ \"you\" later"

result:

 later

Using awk or other methods, how can I extract the substring in the double quotes?

like image 977
user2365346 Avatar asked Oct 26 '25 18:10

user2365346


2 Answers

1st solution: You can make use of gsub function of awk here. Just simply do 2 substitutions with NULL. 1st till 1st occurrence of " and then substitute everything from next " occurrence to everything with NULL and print that line.

awk '{gsub(/^[^"]*"|".*/,"")} 1' Input_file


2nd solution: Using GNU grep solution. Using its -oP option to print matched part and enable PCRE regex option respectively. With regex from starting match till very first occurrence of " and using \K option to forget matched part and then again match everything just before next occurrence of " which will print text between 2 " as per requirement.

grep -oP '^.*?"\K[^"]*' Input_file
like image 91
RavinderSingh13 Avatar answered Oct 28 '25 06:10

RavinderSingh13


Using bash

IFS='"'
read -ra arr <<< "See [ \"you\" later"
echo ${arr[1]}

gives output

you

Explanation: use IFS to inform bash to split at ", read splitted text into array arr print 2nd element (which is [1] as [0] denotes 1st element).

like image 40
Daweo Avatar answered Oct 28 '25 07:10

Daweo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!