Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash variable substitution

Tags:

bash

I have a variable containing four numbers separated by a space, such as for instance:

a="12.3 423.4 11.0033 14.02"

But sometimes, I have a trailing whitespace:

a="12.3 423.4 11.0033 14.02 "

I want to replace the spaces with " & ", and for that, I do:

echo ${a// / & }

Which gives me:

12.3 & 423.4 & 11.0033 & 14.02

or if I have a trailing whitespace:

12.3 & 423.4 & 11.0033 & 14.02 & 

My problem is that I don't know if I'll have a space at the end of my string and I don't want that extra "&" in any case. What would be the most elegant way to avoid this extra character? Is there a way to say "replace if a space and the next character a digit"?

Edit: I knew I could use sed, but since there is a mechanism of variable substitution in bash, I would like to know how could I use it to do what I want. I don't know how to write "not end of line" or "is a digit" in the bash substitution.

like image 480
Maxime Chéramy Avatar asked Sep 11 '26 07:09

Maxime Chéramy


1 Answers

This will remove trailing space if there is any:

a=${a% }

Then you can do your replace:

a=${a// / & }
like image 136
danadam Avatar answered Sep 14 '26 05:09

danadam