LDP/LDP/guide/docbook/abs-guide/neg-offset.sh

27 lines
964 B
Bash
Raw Normal View History

2011-05-03 15:38:48 +00:00
#!/bin/bash
# Bash, version -ge 4.2
# Negative length-index in substring extraction.
2011-08-29 23:59:19 +00:00
# Important: It changes the interpretation of this construct!
2011-05-03 15:38:48 +00:00
stringZ=abcABC123ABCabc
echo ${stringZ} # abcABC123ABCabc
2011-08-29 23:59:19 +00:00
# Position within string: 0123456789.....
2011-05-03 15:38:48 +00:00
echo ${stringZ:2:3} # cAB
# Count 2 chars forward from string beginning, and extract 3 chars.
# ${string:position:length}
# So far, nothing new, but now ...
2011-08-29 23:59:19 +00:00
# abcABC123ABCabc
# Position within string: 0123....6543210
2011-05-03 15:38:48 +00:00
echo ${stringZ:3:-6} # ABC123
# ^
# Index 3 chars forward from beginning and 6 chars backward from end,
#+ and extract everything in between.
# ${string:offset-from-front:offset-from-end}
# When the "length" parameter is negative,
2011-08-29 23:59:19 +00:00
#+ it serves as an offset-from-end parameter.
# See also neg-array.sh.