Harry
Harry

Reputation: 198

Calculate the length of a string in bash

I have the following hexadecimal string

VAR='\x45\x8A\xC8\x4E\x58\xBB\x16\x17\x55\x96\xA5\x26\xD1\xDA\x56\x04\xA7\xBD\x6F\xA5'

I need to find the number of bytes of it which is 20. But if I type

length=${#VAR}
echo "var length: "$length

I get 80. How can I do? Thank you very much in advance!

Upvotes: 2

Views: 1698

Answers (2)

Ivan
Ivan

Reputation: 7277

Use wc

echo $VAR | wc -c

$ wc --help
Usage: wc [OPTION]... [FILE]...
  or:  wc [OPTION]... --files0-from=F
...
The options below may be used to select which counts are printed, always in
the following order: newline, word, character, byte, maximum line length.
  -c, --bytes            print the byte counts

Upvotes: 1

chepner
chepner

Reputation: 531165

It doesn't have 20 bytes; it has 80, since \x45 is 4 individual characters, not a literal representing a single byte. VAR=$'\x45...' would give you the 20-byte string you expect.

Upvotes: 6

Related Questions