nagaraj sherigar
nagaraj sherigar

Reputation: 87

Sed command to extract group of digits

I have 3 statements like the following:

abcdef       (123)
adf4fggggh   (456)
ssff444fgff  (4667)

By using sed command I need to extract last digits i.e 123,456,4667

Upvotes: 1

Views: 313

Answers (3)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed -n '/.*(\([0-9]\{1,\}\))[[:blank:]]*$/ s//\1/p' file.txt
  • posix version with a bit of security (on line that does not correspond)
  • you can add a -\{0,1\} just before the digit class is negative value could occur (same idea with a . if a dotted value could also occur)

Upvotes: 0

Songy
Songy

Reputation: 851

You can do this by substituting. This RegEx will match the entire line, capture the numbers and place the numbers back down.

Assuming that your lines are in a file called file.txt:

sed 's/.*(\([0-9]\+\))/\1/' file.txt

Upvotes: 3

Kent
Kent

Reputation: 195029

grep get the digits between last parentheses :

grep -Po '\d+(?=\)$)'

or

awk -F'[)(]' '{print $(NF-1)}'

Upvotes: 1

Related Questions