Description
In the following example, we want to extract all strings matched [0-9]+(a sequence of digits), and print them one per line.

Note that Script3 is the most efficient one.

Raw Input Desired Output
number 123 number 45 number
number 6 another 7890 more 13579
no numbers in this line
2468086 last 1248163264 no more 
123
45
6
7890
13579
2468086
1248163264
Script and Comments
Script1
[ 1] s/^[^0-9]*([0-9]+)/\1\n/
[ 2] /\n/!d
[ 3] P
[ 4] D
Comments
  1. The `-r' option of GNU sed must be used or you have to escape parentheses and the `+' quantifier.
  2. Each line may contain zero, one or more substrings matched [0-9]+.
  3. A line is treated as repeating sequences of unmatched string (may be empty) followed by a matched string.
  4. The strategy used by this script is as follows:
    • Take the first unmatched-matched sequence,
      insert a newline character after the matched string and
      remove the unmatched one (this is accomplished by Step [1]).
    • After Step [1], the Pattern Space may contain
      • Two lines, where the first one contains only the matched string and the other is the part of the original line which has not been processed yet.
        Step [3] will print the matched string, and Step [4] will delete it and make sed jump to Step [1].
      • One line, (Step [1] failed), implying that there are no more matched strings. In this case, Step [2] will delete it and start a new cycle.
Script2
[ 1] s/^[^0-9]*([0-9]+)/\1\n/
[ 2] /\n/P
[ 3] D
Comments
  1. A neat version.
Script3
[ 1] s/[0-9]+/\n&\n/g
[ 2] s/[^\n]*\n([0-9]*\n)/\1/g
[ 3] s/\n[^\n]*$//p
[ 4] d
Comments
  1. Step [1] will enclose every matched string with a pair of newline characters.
  2. After Step [1], we can treat a line as a interleaving sequence of unmatched strings and matched strings, where two strings are separated by a newline character.
  3. For example, if `X' and `Y' are used to denote an unmatched and a matched string, respectively, then a line can be treated as X \n Y \n X \n Y \n ... \n X
  4. Step [2] removes every X and the newline character following it, making the line be Y \n Y \n ...\n Y \n X.
  5. Step [3] removes the trailing X and the preceding newline character.