0

A string is returned by myString=$(some_command).

The resulting value of myString looks like:

there are spaces in this line.  

What specific bash command can be typed to extract only the last n number of characters after the final space in the resulting value of myString?

For the example value of myString shown above, I would want to extract the 5 characters line.

However, for a different value of myString like "this line has many spaces.", the desired sliced output would be spaces.

1 Answer 1

4

Given a variable

myString='there are spaces in this line.'

you can remove the longest leading component ending in a space using the parameter expansion ${myString##* } e.g.

$ myString='there are spaces in this line.'
$ echo "${myString##* }" 
line.
$
$ myString='this line has many spaces.'
$ echo "${myString##* }"
spaces.
2
  • Your code works. Thank you. But here is the major problem that I see: Your code looks like black magic because it does not explain HOW it works. This means that a reader is not easily able to apply the underlying concepts to other problems. Are you willing to add a paragraph or two explaining HOW your code works?
    – CodeMed
    Commented Apr 3, 2018 at 22:46
  • @CodeMed I have now added a linked reference - I hope that provides the additional explanation that you want Commented Apr 3, 2018 at 22:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .