| 1 | #!/bin/bash |
| 2 | |
| 3 | var1=abcd-1234-defg |
| 4 | echo "var1 = $var1" |
| 5 | |
| 6 | t=${var1#*-*} |
| 7 | echo "var1 (with everything, up to and including first - stripped out) = $t" |
| 8 | # t=${var1#*-} works just the same, |
| 9 | #+ since # matches the shortest string, |
| 10 | #+ and * matches everything preceding, including an empty string. |
| 11 | # (Thanks, Stephane Chazelas, for pointing this out.) |
| 12 | |
| 13 | t=${var1##*-*} |
| 14 | echo "If var1 contains a \"-\", returns empty string... var1 = $t" |
| 15 | |
| 16 | |
| 17 | t=${var1%*-*} |
| 18 | echo "var1 (with everything from the last - on stripped out) = $t" |
| 19 | |
| 20 | echo |
| 21 | |
| 22 | # ------------------------------------------- |
| 23 | path_name=/home/bozo/ideas/thoughts.for.today |
| 24 | # ------------------------------------------- |
| 25 | echo "path_name = $path_name" |
| 26 | t=${path_name##/*/} |
| 27 | echo "path_name, stripped of prefixes = $t" |
| 28 | # Same effect as t=`basename $path_name` in this particular case. |
| 29 | # t=${path_name%/}; t=${t##*/} is a more general solution, |
| 30 | #+ but still fails sometimes. |
| 31 | # If $path_name ends with a newline, then `basename $path_name` will not work, |
| 32 | #+ but the above expression will. |
| 33 | # (Thanks, S.C.) |
| 34 | |
| 35 | t=${path_name%/*.*} |
| 36 | # Same effect as t=`dirname $path_name` |
| 37 | echo "path_name, stripped of suffixes = $t" |
| 38 | # These will fail in some cases, such as "../", "/foo////", # "foo/", "/". |
| 39 | # Removing suffixes, especially when the basename has no suffix, |
| 40 | #+ but the dirname does, also complicates matters. |
| 41 | # (Thanks, S.C.) |
| 42 | |
| 43 | echo |
| 44 | |
| 45 | t=${path_name:11} |
| 46 | echo "$path_name, with first 11 chars stripped off = $t" |
| 47 | t=${path_name:11:5} |
| 48 | echo "$path_name, with first 11 chars stripped off, length 5 = $t" |
| 49 | |
| 50 | echo |
| 51 | |
| 52 | t=${path_name/bozo/clown} |
| 53 | echo "$path_name with \"bozo\" replaced by \"clown\" = $t" |
| 54 | t=${path_name/today/} |
| 55 | echo "$path_name with \"today\" deleted = $t" |
| 56 | t=${path_name//o/O} |
| 57 | echo "$path_name with all o's capitalized = $t" |
| 58 | t=${path_name//o/} |
| 59 | echo "$path_name with all o's deleted = $t" |
| 60 | |
| 61 | exit 0 |