There are also some ways to perform string "chopping" via parameter expansion, which are frequently useful for trimming paths. The "${myvar#prefix}" form removes one occurrence of prefix from the variable's expansion:
$ ta='type:json' $ printf 'Type: %s\n' "${ta#type:}" Type: json
We can chop a string from the end of the value instead using % instead of #:
$ ta='type:json' $ printf 'Field name: %s\n' "${ta%:*}" Field name: type
Note that the stripped string can include wildcards: * to match any number of characters, or ? to match one. In the preceding example, we stripped :*, or the rightmost string following a colon.
If you want to trim a pattern with literal asterisks, you need to escape or quote them:
$ text='*WARNING' $ printf '%s\n' "${text#\*}" WARNING $ printf '%s\n' "${text#'*'}" WARNING
The preceding forms will will lean toward removing smaller occurrences of the pattern rather than larger ones. If you want to chop the longest possible match of a pattern with * in it, double the applicable sign: # becomes ##, and % becomes %%. The first is useful for stripping an entire leading path with */:
$ path=/usr/local/myscript/bin/myscript $ printf 'Filename with path removed: %s\n' "${path##*/}"
Filename with path removed: myscript