5

In one of my bash scripts I needed to obtain the last part of a colon delimited string. For example I needed to grab the numeric 289283 value from the following value:

OK: DriveC-ReadBytesPerSec: 289283

After some trial and error I arrived at the following:

READRESULT="OK: DriveC-ReadBytesPerSec: 289283"
echo ${READRESULT#*:*:*}

Which outputs 289283.

The problem is that whilst it gets the job done, I don't fully understand why ${READRESULT#*:*:*} produces the correct result.

Can anyone explain how this globbing expression works?

2
  • 1
    Alternatively, you could use ${READRESULT##*: }, to strip everything until the last colon followed by a space. Note that ${READRESULT#*:*:*} has a leading space, which could cause trouble down the line; and as peth writes the last * isn't matching anything. ${READRESULT#*:*: } is probably what you meant to write. Jun 27, 2011 at 11:42
  • @gilles - as I said, it was pure trial and error whilst under some time pressure :)
    – Kev
    Jun 27, 2011 at 11:47

1 Answer 1

11

From man bash:

${parameter#word}
${parameter##word}

Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted.

Your pattern is *:*:*, and bash will try to remove the shortest matching prefix:

  • OK: for the first *:
  • DriveC-ReadBytesPerSec: for the second *:
  • and nothing for the last *, because it goes for the shortest match.

Compare:

$ # shortest match without surplus *
$ echo ${READRESULT#*:*:}
289283
$ # going for longest match now; the last * will swallow the number
$ echo ${READRESULT##*:*:*}

$ # longest match without the last *
$ echo ${READRESULT##*:*:}
289283
$ # no need to repeat *: because * matches everything before the last : anyway
$ echo ${READRESULT##*:}
289283

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .