itsh
itsh

Reputation: 1123

How to extract numbers using sed

How do I extract the digit(s) before last dash(-) and .zip from the following string - fooBar-5.3.8-78642.zip using sed?

I want to extract 8-78642.

Upvotes: 0

Views: 3265

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

To get a unified and portable solution(will work on all sed implementations) use the following approach based on Basic Regular Expression (BRE):

echo "fooBar-5.3.8-78642.zip" | sed 's/.*\([[:digit:]]\+\-[[:digit:]]\+\)\.zip$/\1/'

Basic Regular Expression (BRE) is the default in sed (and similarly in grep)

----------------------------------------------------------------

The second simple alternative(without regular expression) using awk language:

echo fooBar-5.3.8-78642.zip | awk -F"." '{print $3}'

-F"." - . here is treated as field separator

$3 - points to the third field i.e. 8-78642

----------------------------------------------------------------

And the last simple and fast alternative is using cut command:

echo "fooBar-5.3.8-78642.zip" | cut -d'.' -f3

The output(for each of the above approaches):

8-78642

Upvotes: 1

Barmar
Barmar

Reputation: 780984

Match the part you want with a capture group, and then replace the whole line with just that back-reference.

echo "fooBar-5.3.8-78642.zip" | sed -r 's/.*\.([0-9]+-[0-9]+)\.zip$/\1/'

Upvotes: 2

Related Questions