Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the number of characters in a Bash variable [duplicate]

Tags:

linux

bash

How can I count all characters in a bash variable? For instance, if I had

"stackoverflow" 

the result should be

"13" 
like image 477
lacrosse1991 Avatar asked Mar 24 '13 07:03

lacrosse1991


People also ask

How do I count strings in bash?

'#' symbol can be used to count the length of the string without using any command. `expr` command can be used by two ways to count the length of a string. Without `expr`, `wc` and `awk` command can also be used to count the length of a string.

How do I count character size in Linux?

The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal. The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.

How do you count increments in bash?

Increment Bash Variable with += Operator Another common operator which can be used to increment a bash variable is the += operator. This operator is a short form for the sum operator. The first operand and the result variable name are the same and assigned with a single statement.


2 Answers

Using the ${#VAR} syntax will calculate the number of characters in a variable.

https://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

like image 96
SteveP Avatar answered Sep 18 '22 15:09

SteveP


Use the wc utility with the print the byte counts (-c) option:

$ SO="stackoverflow" $ echo -n "$SO" | wc -c     13 

You'll have to use the do not output the trailing newline (-n) option for echo. Otherwise, the newline character will also be counted.

like image 36
mihai Avatar answered Sep 19 '22 15:09

mihai