String chopping

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' ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.