The portable "replacements" are simple if the offset (and the length) are static. For example, the following code would print the substring of "foo" consisting of only the last two characters:
var=foo # Replace the bashism ${var:1} with: echo ${var#?}
The length can then be limited with additional pattern-matching removal expansions:
var="portable code" # Replace the bashism ${var:3:5} with the following code # Offset is 3, so we use three ? (interrogation) characters: part=${var#???} # Length is 5, so we use five ? characters: echo ${part%${part#?????}}
As it can be seen, it is not impossible to replace a substring expansion.
The portable code becomes slightly more complex if the offset and/or the length are dynamic. I leave that as an exercise for the readers.
Feel free to post your code as a comment (use the <pre> tags, please) or in another public way. My own response is already scheduled to be published next week at the same time as usual.
Note: substring expansions can also be replaced with a wide variety of external commands. This is a pure-POSIX shell scripting example.
Probably is only a coincidence, but yesterday I searched your blog for substrings... :)
ReplyDeleteThanks for sharing, as usual.