1

I'm trying below

a = device.1.2

echo $a should print 1.2

Tried with sed 's/[a-z]//g' a

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
Alex
  • 11
  • 2
  • 1
    BTW, note that `echo $a` is itself buggy; _always_ `echo "$a"`. See [I just assigned a variable, but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Feb 11 '21 at 16:20

1 Answers1

4

First thing first please make sure your shell variable doesn't have space while assigning value to it, so have it like this: a="device.1.2". With your shown samples, could you please try following once.

Have it with parameter substitution way: Where we need not to use an external program to get the value.

echo "${a#*.}"


OR with sed: Since OP was trying sed so adding one sed solution here, this nice command was given by Benjamin see comments for same.

echo "$a" | sed 's/^[^.]*\.//'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    Simpler sed substitution: `s/^[^.]*\.//` – Benjamin W. Feb 11 '21 at 15:41
  • 1
    Maybe `sed 's/[^-+.0-9]//g'` to remove all characters except digits, dots and plus or minus signs. Note that the `-` must be 'first' (as shown) or 'last'. It isn't clear how general the numbers are, and this could end up with some unwanted characters; tune the list to suit the actual requirements. It won't handle exponential notation (`-3.14159E-23`) very well (nor hexadecimal `data.0x03grid`); handling those requires considerably more refined techniques. – Jonathan Leffler Feb 11 '21 at 15:45
  • 2
    No reason to use sed for character set replacement, bash can do that built-in. `${a//[^[:digit:].]/}` – Charles Duffy Feb 11 '21 at 15:45
  • @CharlesDuffy, sure sir Thank you(I added parameter expansion answer too since OP was using `sed` so I added it as per Benjamin's nice suggestion), I could delete the answer, you should really post this Good answer. @ Jonathan Leffler, Thank you sir for another nice variant, cheers. – RavinderSingh13 Feb 11 '21 at 15:48
  • 1
    @CharlesDuffy: That assumes Bash or a Bash-compatible (enough) shell. The question tag is plain [tag:shell], so the notation might not be available. But the character class notation is useful. It works (somewhat to my surprise) on macOS 10.14.6 with Bash 3.2.57 (as amended by Apple), so it is likely good on all plausible versions of Bash. – Jonathan Leffler Feb 11 '21 at 15:48