1

I have a pattern that looks something like this .

var a ; 
var b;

var obj = {
aa : 'This is what I want'
};

I want the text between aa : ' and '};

There might be multiple occurrences of this, but I would like to have the first one.

I have tried awk , grep and sed. But none of them gave me the perfect result, but spit out entire code.

What I have tried till now :

grep -Po "aa : \K.*(?= \'};)"
sed -e 's/aa :\(.*\)\n};/\1/'

6 Answers 6

2
awk -F"'" -v RS=";" '/\naa/{print $2;exit}'
Sign up to request clarification or add additional context in comments.

1 Comment

It does not work. Please add a line between aa : 'This is what I want' and ;} and try again
0

Please try the following:

awk 'BEGIN {Found = 0;} /^aa :/{Found = 1; } /^};/{Found = 0;} {if(Found) {print $0;}}'

2 Comments

How do you run it?
I'm getting: aa : 'This is what I want'};
0

Using grep -oP you can use match reset \K:

grep -oP "\baa\s*:\s*'\K[^']+" file

This is what I want

Comments

0

If I really bend it in AWK:

BEGIN {
    RS="- -it is not the spoon that bends, it is only yourself"
    FS="(aa : '|'};)"
}
{
    print $2
}

Comments

0

With GNU awk for multi-char RS:

$ awk -v RS="aa[[:space:]]*:[[:space:]]*'[^']*'[[:space:]]*}[[:space:]]*;" -F"'" '{$0=RT; print $2; exit}' file
This is what I want

Comments

0

Here is a another solution, using sed:

echo $'var obj = {\naa: \'This is what I want\'\n};
var obj2 = {\naa: \'Unwanted\'\n};' | \
sed -ne $'/aa:/ {N;s/aa: \'\\(.*\\)\'\\n.*/\\1/;T;p;q}'

T;p;q prints the replacement on the first match and quits, and continues with next line otherwise.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.