I wrote the following script to test the "printable characters" character class, as described here.

#!/bin/sh

case "foo" in
    *[:print:]*) echo "found a printable character" ;;
    *) echo "found no printable characters" ;;
esac

I expect this script to output found a printable character, at least one (in fact, all) characters in "foo" are printable. Instead, it outputs "found no printable characters". Why are the characters in "foo" not recognized as printable characters?

有帮助吗?

解决方案

The string [: is only special inside a bracket expression and bracket expressions are themselves introduced by [. So your example should be:

case "foo" in
    *[[:print:]]*) echo "found a printable character" ;;
    *) echo "found no printable characters" ;;
esac

If this seems cumbersome, think about for example how you would specify a pattern which should match a lowercase letter or a digit but not an upper case letter.

For more information see the section of the POSIX spec detailing bracket expressions in regular expressions. Bracket expressions in shell patterns are like bracket expressions in regular expressions, except for the treatment of ! and ^. (Though otherwise there are other differences between shell patterns and regexes, outside the context of bracket expressions).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top