Use sed instead of grep :
echo 12345 | sed -n '/^\([0-9]\{1,4\}\).*/s//\1/p'
This corresponds to 4 digits at the beginning of a line followed by something, saves only the digits and prints them. -n prevents printing lines otherwise. If a string of numbers can also appear in the middle line, you will need a slightly more complex command.
In fact, ideally, you'll use sed with PCRE regular expressions, since you really need a non-greedy match. However, until a reasonable approximation, you can use: (Semi-solution for a more complex problem ... now deleted!)
Since you want the first line to be up to 4 digits long per line, just use sed to delete any numbers, and then print the number line:
echo abc12345 | sed -n '/^[^0-9]*\([0-9]\{1,4\}\).*/s//\1/p'
This corresponds to a line without digits, followed by 1-4 digits, followed by something, saves only the digits and prints them.
Jonathan leffler
source share