Interview Prep/Shell Scripting/Text processing: grep, sed, awk, cut, sort, uniq

What are POSIX character classes and why use them?

IntermediateConceptText processing: grep, sed, awk, cut, sort, uniq
Answer

Classes like [[:digit:]], [[:alpha:]], [[:alnum:]], [[:space:]], [[:upper:]] and [[:punct:]] work in grep, sed, awk, tr and Bash patterns, and respect the locale.

grep -E '^[[:space:]]*#' f          # comment lines with optional indentation
tr -cd '[:alnum:]._-' <<<"$name"    # keep only safe characters
[[ $v == +([[:digit:]]) ]]          # extglob: only digits

Ranges like [a-z] can match unexpected characters in some locales; classes (or LC_ALL=C) avoid that.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Text processing: grep, sed, awk, cut, sort, uniq