1

I have a file with following type of expression in every line "Age=22 years and Height=6 feet", I want to extract Age and height numbers only.

I have tried

grep -oP  '(?<=Age=)[^years]+' $f | awk '{ printf "%d \n",$1; }

and get age correctly. How can I get both Age and height. When I try nested pattern match i get height only.

This is the pattern I've tried

grep -oP  '(?<=Age=)[^years]+.+(?<=Height=)[^feet]+' $f | awk '{ printf "%d \n",$1; }
1
  • 2
    Are the numbers always represented as positive integers? "Number" can mean anything like 2.3, 0x45, -1.3e30.
    – Kusalananda
    Jul 8, 2020 at 6:43

3 Answers 3

7

This is not doing what you think it does, it works only by accident:

[^years]+

It means, match any character except y, e, a, r and s at least once.

Also, instead of Look-behind assertion, I would use keep-out. It has the benefit that it can be of variable length, then you can easily match both Age and Height.

(Age|Height)=\K

Then, instead of making a negative match, use a positive one, matching only numbers:

grep -Po '(Age|Height)=\K\d+'

--

$ echo "Age=22 and Height=6" | grep -Po '(Age|Height)=\K\d+'
22
6
2
  • Thanks, how can i print output like this 22 6 in a row Jul 8, 2020 at 12:32
  • 1
    you could simply pipe to xargs --> ... | xargs
    – pLumo
    Jul 8, 2020 at 12:46
2
$ echo 'Age=22 years and Height=6 feet' | awk -F'[= ]' '{print $2, $6}'
22 6
1

I have a file with following type of expression in every line "Age=22 years and Height=6 feet"

With sed that has the -E option.

sed -E 's/[^[:digit:]]+/ /g;s/^ //' <<< "Age=22 years and Height=6 feet"

Or if it is a file point sed to it.

sed -E 's/[^[:digit:]]+/ /g;s/^ //' file.txt

To add both Age and Height to the pattern.

sed -E 's/^Age=([[:digit:]][^ ]*).*Height=([[:digit:]][^ ]*).*/\1 \2/' file.txt
2
  • 1
    You don't need -E for your first example, just use * instead of +. You only need it to avoid escaping the parentheses in your last example (but it will work fine without the -E if you use \( and \)). You also don't need the g modifier when you're anchoring a regex to the beginning of the line (^) since that will never match more than once.
    – terdon
    Jul 8, 2020 at 17:32
  • @terdon, thank you for that wonderful comment, updated accordingly.
    – Jetchisel
    Jul 8, 2020 at 22:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .