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.

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.
  • 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 Apr 3 '18 at 22:46
  • @CodeMed I have now added a linked reference - I hope that provides the additional explanation that you want – steeldriver Apr 3 '18 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.