Ash
Ash

Reputation: 896

Why is this grep <regex> not working?

The following regex with grep doesn't seem to be working: grep "(?=\_\(\").*?(?=\"\))" ./testfile.js

testfile.js is as follows:

asoijf oaisdjf _("string 1") fodijsasf _("string 2")
fasdoij _("string 3");
console.log(_("string 4"));

My aim is to grab all the strings enclosed in _() function calls, without greps -P flag (the option doesn't exist for me). Expected output would be:

string 1
string 2
string 3
string 4

Any idea's?

Update: The -P flag was removed from bash in my version of mac (see grep -P no longer works how can I rewrite my searches)

Upvotes: 0

Views: 951

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following awk and let me know if this helps you.

grep -oE '_\([^\)]*' Input_file | cut -c3-

Output will be as follows.

"string 1"
"string 2"
"string 3"
"string 4"

EDIT: Since OP doesn't have -P option in it's O.S so providing an awk approach here too.

awk '{
  while($0){
    match($0,/_\([^\)]*/);
    st=RSTART;
    le=RLENGTH;
    if(substr($0,RSTART+2,RLENGTH-2)){
      print substr($0,RSTART+2,RLENGTH-2)
};
  $0=substr($0,st+va+3)
}
}
'   Input_file

Upvotes: 1

P....
P....

Reputation: 18351

grep -oP '_\("\K[^"]+' inputfile
string 1
string 2
string 3
string 4

Here, -o will print only the matched result, not the whole line. \K will be used for the look behind, Means matches the string left of \K but do not print it. [^"]+ means anything except " one or more time.

Or without -P option:

grep -oE '_\("[^"]+' inputfile|cut -d'"' -f2
string 1
string 2
string 3
string 4

Upvotes: 0

Related Questions