How to Use sed to Extract Numbers from a String


Often you may want to use sed to extract only numbers from a string.

You can use the following syntax to do so:

sed "s/[^0-9]//g" employees.txt

This particular example extracts only the numbers from each line in the file named employees.txt.

Here is what the various sed commands do:

  • s: Used to “substitute” one pattern for another pattern
  • [^0-9]: Matches all characters in the string that are not numbers
  • //: Replaces the matched characters with nothing, which effectively removes all characters that are not numbers
  • g: Specifies that this substitution should be made “globally”, i.e. for all occurrences

The following example shows how to use this syntax in practice.

Example: How to Use sed to Extract Numbers from a String

Suppose that we have the following file named employees.txt that contains ID numbers for various employees at some company:

Suppose that we would like to extract only the numbers from each employee ID.

We can use the following syntax to do so:

sed "s/[^0-9]//g" employees.txt

The following screenshot shows how to use this syntax in practice:

sed extract numbers from string

Notice that this returns only the numbers from each line in the file.

Note that we could also use the > command to save these results to a new file:

sed "s/[^0-9]//g" employees.txt > employees_new.txt

This particular example would extract the numbers from each line in the file named employees.txt and save the results to a new file named employees_new.txt.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Extract All Lines Containing a Pattern
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply