3

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.

tripleee
  • 175,061
  • 34
  • 275
  • 318
r.sendecky
  • 9,933
  • 9
  • 34
  • 62
  • Does this answer your question? [How to use sed/grep to extract text between two words?](https://stackoverflow.com/questions/13242469/how-to-use-sed-grep-to-extract-text-between-two-words) – tripleee Aug 10 '20 at 17:53

4 Answers4

7

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.

Andrew Logvinov
  • 21,181
  • 6
  • 52
  • 54
3

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
Floris
  • 45,857
  • 6
  • 70
  • 122
  • This is a bit excessive... it "eats" every part of the expression - but it does spell out how to make a regex work for you in a situation like this. – Floris Jan 31 '13 at 04:59
1

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

awk '/crop=([0-9:]*?)/\1/'
Matthew
  • 9,851
  • 4
  • 46
  • 77
0

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 (%%)
alp
  • 642
  • 5
  • 13