r.sendecky
r.sendecky

Reputation: 10363

Extract string located after or between matched pattern(s)

Given a string "pos:665181533 pts:11360 t:11.360000 crop=720:568:0:4 some more words"

Is it possible to extract string between "crop=" and the following space using bash and grep?

So if I match "crop=" how can I extract anything after it and before the following white space?

Basically, I need "720:568:0:4" to be printed.

Upvotes: 3

Views: 11608

Answers (4)

alp
alp

Reputation: 712

yet another way with bash pattern substitution

PAT="pos:665181533 pts:11360 t:11.360000 crop=720:568:0:4 some more words"
RES=${PAT#*crop=}
echo ${RES%% *}
  • first remove all up to and including crop= found from left to right (#)
  • then remove all from and including the first space found from right to left (%%)

Upvotes: 0

Floris
Floris

Reputation: 46375

I would use sed as follows:

echo "pos:665181533 pts:11360 t:11.360000 crop=720:568:0:4 some more words" | sed 's/.*crop=\([0-9.:]*\)\(.*\)/\1/'

Explanation:

s/          : substitute
.*crop=     : everything up to and including "crop="
\([0-9.:]\) : match only numbers and '.' and ':' - I call this the backslash-bracketed expression
\(.*\)      : match 'everything else' (probably not needed)
/\1/        : and replace with the first backslash-bracketed expression you found

Upvotes: 3

Matthew
Matthew

Reputation: 9949

I think this will work (need to recheck my reference):

awk '/crop=([0-9:]*?)/\1/'

Upvotes: 1

Andrew Logvinov
Andrew Logvinov

Reputation: 21831

I'd do it this way:

grep -o -E 'crop=[^ ]+' | sed 's/crop=//'

It uses sed which is also a standard command. You can, of course, replace it with another sequence of greps, but only if it's really needed.

Upvotes: 7

Related Questions