Joe
Joe

Reputation: 991

How to correctly use regex group capture with the grep command?

I've got this text:

Paket telah dikirim melalui TIKI, no.resi 885000130000, Cek status pesanan di https://tiki.id/resi/

And I want to grep only the 885000130000 part this is what I have tried:

echo "$text" | grep -Eo 'Paket telah dikirim melalui TIKI, no\.resi (.*),'

But the result is always

Paket telah dikirim melalui TIKI, no.resi 885000130000, 

I just want grep to show the number only 885000130000. How do I do it ?

Upvotes: 0

Views: 119

Answers (5)

Claes Wikner
Claes Wikner

Reputation: 1517

awk -F'[, ]' '{print $8}' file

output
885000130000

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203522

If this isn't all you need:

$ awk '{print $7+0}' file
885000130000

then edit your question to clarify your requirements. If you need to match the rest of that string then either of these might be what you need instead:

$ awk '/Paket telah dikirim melalui TIKI, no\.resi/{print $7+0}' file
885000130000

$ awk 'sub(/Paket telah dikirim melalui TIKI, no\.resi/,""){print $0+0}' file
885000130000

It just depends on the unspoken details of your requirements. Any of the above will work efficiently, robustly, and portably with any awk in any shell on any UNIX box and are trivial to modify if/when your requirements change.

Upvotes: 1

RavinderSingh13
RavinderSingh13

Reputation: 133518

If your string/Input_file is same as shown example then following may also help you here.

awk '{sub(/.*no.resi /,"");sub(/,.*/,"")} 1' Input_file

Upvotes: 1

Walter A
Walter A

Reputation: 20002

With sed you only print the lines with the option -n followed by .../p. This solution only shows one match per line.

echo "${text}" | sed -n 's/.*Paket telah dikirim melalui TIKI, no\.resi (.*),.*/\1/p'

In your current example you only want ALL the digits:

echo "${text}" | grep -Eo "[0-9]*"

or (when you have other numbers) use 2 grep's:

echo "${text}" | 
   grep -Eo 'Paket telah dikirim melalui TIKI, no\.resi [0-9]*,' | grep -Eo "[0-9]*"

Upvotes: 0

Joe
Joe

Reputation: 991

SOLVED:

echo "$text" | grep -oP 'Paket telah dikirim melalui TIKI, no\.resi \K(\d+)'

Upvotes: 1

Related Questions