Bash: String Length – How To Find Out


If you often create Bash scripts, you may sometimes need to get the length of a string or find out the length of a variable that stores some string.

This short note shows how to find out the length of a string from the Linux command line and how to count the length of the each line in a file.

You will also see how to get the length of a string if it is stored in a variable in Bash and then assign that calculated number of characters to another variable.

Cool Tip: Needs to pass arguments to a Bash script? Make it to print usage and exit if they are not provided! Follow the best practice! Read more →

The Length of a String in Bash

Find out the length of a string in Bash, using expr command:

$ expr length "Find out the length of this string from Linux Bash shell."
57

Get the length of a line in Bash, using wc command:

$ echo -n "Get the length of this line in Bash" | wc -c
35

Get the length of a line in Bash, using the awk command:

$ echo "--- What about this line? ---" | awk '{print length}'
29

The Length of the Each Line in a File

Cool Tip: Make your Bash script interactive! Teach it to prompt for “Yes/No” confirmation. Read more →

Lets say we have a file with the following content:

$ cat file
This is the first line
This is the second line
This is the third line
This is the fourth line
This is the fifth line
And so on

Get the length of the each string in a file:

$ awk '{ print $0 " = " length($0) }' file
This is the first line = 22
This is the second line = 23
This is the third line = 22
This is the fourth line = 23
This is the fifth line = 22
And so on = 9

Print the lengths only:

$ awk '{ print length($0) }' file
22
23
22
23
22
9

The Length of a Variable in Bash

 

It is impossible to imagine Bash scripts without wide use of different variables.

 

This is a very common situation when you store some string in a variable and need to find out its length to pass it through some if...then...else construction, for example.

See how to calculate the length of a variable in Bash and how to assign its value to another variable, if needed.

Cool Tip: Do not be a bore! Add COLORS to your Bash script! Make it look AWESOME! Read more →

Find out the length of a string stored in a variable:

$ VAR="This string is stored in a variable VAR"
$ echo ${#VAR}
39

Get the length of a string stored in a variable and assign it to another variable:

$ VAR="This string is stored in a variable VAR"
$ VAR_LENGTH=${#VAR}
$ echo $VAR_LENGTH
39


Article Number: 482
Posted: Mon, Feb 18, 2019 2:30 PM
Last Updated: Mon, Feb 18, 2019 2:30 PM

Online URL: http://kb.ictbanking.net/article.php?id=482