The only way to do this in "Bourne compatible" is to use external utilities.
Alternatively, to type one of c, you can use xxd and expr (for example):
$ output="$(printf "x\n\n"; printf "X")" # get the output ending in "X". $ printf '%s' "${output}" | xxd -p # transform the string to hex. 780a0a58 $ hexstr="$(printf '%s' "${output}" | xxd -p)" # capture the hex $ expr "$hexstr" : '\(.*\)..' # remove the last two hex ("X"). 780a0a $ hexstr="$(expr "$hexstr" : '\(.*\)..') # capture the shorter str. $ printf "$hexstr" | xxd -p -r | wc -c # convert back to binary. 3
Shortened:
$ output="$(printf "x\n\n"; printf "X")" $ hexstr="$(printf '%s' "${output}" | xxd -p )" $ expr "$hexstr" : '\(.*\)..' | xxd -p -r | wc -c 3
The xxd command is used to convert it to a binary file.
Note that wc will not work with many UNICODE characters (multibyte characters):
$ printf "Voilà" | wc -c 6 $ printf "★" | wc -c 3
It will print the number of bytes, not characters.
The length of the variable ${#var} will also fail in older shells.
Of course, to run this in the Bourne shell, you must use `…` instead of $(…) .
source share