Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print POSIX character class

Given a class, such as

[:digit:]

I would like the output to be

0123456789

Note, the method should work for all POSIX character classes. Here is what I have tried

$ printf %s '[:digit:]'
[:digit:]

§ Character classes

like image 689
Zombo Avatar asked Mar 19 '23 02:03

Zombo


2 Answers

I'm sure there's a better way but here's a brute force method:

for i in {0..127}; do 
    char=$(printf \\$(printf '%03o' "$i"))
    [[ $char =~ [[:alpha:]] ]] && echo "$char"
done

Loop through all the decimal character values, convert them to the corresponding ASCII character and test them against the character class.

The range might be wrong but the check seems to work.

As others have mentioned in the comments, it is also possible to use the == operator instead of the =~ in this case, which may be slightly faster.

like image 129
Tom Fenech Avatar answered Apr 01 '23 15:04

Tom Fenech


$ seq 126 | awk '{printf "%c", $0}' | grep -o '[[:digit:]]'
0
1
2
3
4
5
6
7
8
9
like image 38
Zombo Avatar answered Apr 01 '23 15:04

Zombo