[Chapter 9] 9.7 String Editing in ksh and bash
Author: Jerry Peek, Tim O'Reilly & Mike Loukides
Date: 1998-08-04T21:35:00Z

#

| Chapter 9 Saving Time on the Command Line |

## 9.7 String Editing in ksh and bash

The C shell's string editing operators (9.6) can be used with shell variables and, in some cases, with command history. Those operators also work with bash history. But the Korn shell and bash have a different way to edit shell variables. Table 9.1 shows them:

Table 9.1: ksh and bash String Editing Operators
Operator | Explanation
--- | ---
${variable#pattern} | Delete the shortest part of pattern that matches the beginning of variable's value. Return the rest.
${variable##pattern} | Delete the longest part of pattern that matches the beginning of variable's value. Return the rest.
${variable%pattern} | Delete the shortest part of pattern that matches the end of variable's value.Return the rest.
${variable%%pattern} | Delete the longest part of pattern that matches the end of variable's value.Return the rest.

The patterns can be filename wildcard characters: `*`, `?`, and `[]`; with string editing operators, wildcards match strings in the same way they match filenames. (These are not sed-like regular expressions.) The first two operators, with `#`, edit variables from the front. The other two, with `%`, edit from the end. Here's a system for remembering which does what: you put a number sign (`#`) at the front of a number and a percent sign (`%`) at the end of a number.

Time for some examples. The variable var contains /a/b/c/d/e.f.g:

>     Expression   Result

>     ${var}   /a/b/c/d/e.f.g
>     ${var#/*/}   b/c/d/e.f.g
>     ${var##/*/}   e.f.g
>     ${var%.*}   /a/b/c/d/e.f
>     ${var%%.*}   /a/b/c/d/e
>     ${var%%/*/}   /a/b/c/d/e.f.g
>     ${var%%/*}
>     ${var%/b*}   /a
>     ${var%%/b*}   /a

How about a practical example? The PATH variable (6.4) is a string separated by colons (`:`). Let's say you want to remove the last directory from the system path and add `$HOME/bin` in place of the last directory. You'd type this command, or put a line like this in your .profile:

>     PATH=${PATH%:*}:$HOME/bin

Because the `${PATH%:*}` has a single `%`, that operator removes the least it can: just the last colon plus the directory name after it. After string editing, the rest of the PATH has `:$HOME/bin` appended to it. The new value is saved as the new PATH.

The Bourne shell's parameter substitution operators (45.12) look similar, but they're mostly useful for shell programming.

- JP

9.6 String Editing (Colon) Operators |  | 9.8 Filename Completion: Faster Filename Typing