Tuesday, July 26, 2022

[SOLVED] Why can't extract number in a string with sed?

Issue

I can extract port number in the string:

s="2017-04-17 08:16:14 INFO     connecting lh3.googleusercontent.com:443 from 111.111.111.111:26215"
echo $s  | sed  's/\(.*\):\(\d*\)/\2/'
26215

Almost the same knowledge,i want to extract number following "#" in a string:

s="alsa_output.pci-0000_09_00.6.analog-stereo.monitor/#4"
echo $s | sed   's/\#\([0-9]\)/\1/'
alsa_output.pci-0000_09_00.6.analog-stereo.monitor/4
echo $s | sed   's/#\([0-9]\)/\1/'
alsa_output.pci-0000_09_00.6.analog-stereo.monitor/4

Why the output is not the number "4" ?


Solution

You're substituting "#4" with "4", but not changing the front part of the string. In your first example, the ".*" is gobbling up the first part. By analogy:

echo $s | sed 's/.*\#\([0-9]\)/\1/'


Answered By - bg2b
Answer Checked By - Robin (WPSolving Admin)