Simple awk question

Hi All,
A very silly question:
How to just print the integer attached a particular string in a line by awk?
Ex:
Happy_world_foo123...So i just want the value 123 to be printed on the line where we have string "foo".
Thanks

What have you tried so far? Must it be awk and when why?
Answers that show up before the OP answers will be moderated. Thanks for your understanding!

Hi Help!!
I have been searching through a particular value that need to be printed separately.
Suppose,
Happy_world_foo-123.
So to search a string with foo and just to print the value 123,on a line from a text file.
Do anyone have any idea.
Thanks

awk -F"-" '/foo/ {print$2}' /tmp/yourfile

You did change the line in your two example, so not sure how to trigger to get the value. (change from foo123 to foo-123)

Hi Jotne,
It is Just foo123.
So a line with Happy_world_foo123.I just want 123 to be printed when we have string foo in a line.
Thanks

echo "Happy_world_foo123" | awk -F"foo" '/foo/ {print$2}'

This search for all line with foo and prints all after it.
If you have other characters after number or more than one foo in same line, this does not work.

A hint:

var='Happy_world_foo123'

echo ${var#*foo}
123

Thanks a lot Jotne

Awk example works on all lines, but not the echo example

var='Happy_world_foo123
Happy me 2
Nobody like my foo6564'

echo gives

echo "${var#*foo}"
123
Happy me 2
Nobody like my foo6564

or

echo ${var#*foo}
123 Happy me 2 Nobody like my foo6564

Here are two ways to get what I believe was requested:

echo using sed:
sed -n '/foo/s/[^0-9]*\([0-9]*\).*/\1/p' in
echo using ask:
awk '/foo/{if(match($0, /[0-9]+/)) printf("%s\n", substr($0, RSTART, RLENGTH))}' in

assuming that the input lines you want to process are in a file named in . Note that I don't see anything asking for the digits to be printed only if they follow "foo".

$ echo Happy_world_foo123 | sed '/foo/s/[^0-9]//g'
123

How about printing $NF and checking for numeric fields and using sub to remove characters..?

$ echo Happy_world_foo123 | sed '/foo/s/[^0-9]//g'

Does not work on this:

var='Happy_world_foo123
Happy me 2
Nobody like my foo6564'
echo "$var" | sed '/foo/s/[^0-9]//g'
123
Happy me 2
6564
$ echo "$var" | nawk '{gsub("[A-Za-z_]","",$0)}1'
123
2
6564

2 should not be printed.

Line 2 in example does not contain "foo"

$ echo "$var" | nawk '/foo/{gsub("[A-Za-z_]","",$0);print}'
123
6564
sed -n 's/.*foo//p'

If there are further characters behind the digits:

sed -n 's/.*foo\([0-9]*\).*/\1/p'
awk -Ffoo 'NF>1{print $2+0}'