Bash

Bash Find String

Bash Find String

In this topic, we've demonstrated about finding the length of a string in Bash Scripting.

The total number of characters in any string indicates the length of a string. In some cases, we'd got to realize the length of a string to perform some specific tasks. Most of the programming languages have their own built-in functions to calculate the amount of characters. However, Bash doesn't contain such sort of built-in functions. But there are several ways in which we will use to seek out the length of a string in Bash Scripting.

Bash StringLength

To calculate the length of a string, we will use any of the subsequent syntax:

1. ${#string} 

2. expr length "$string" 

3. expr "$string" :'.*' 

4. $str | wc -c 

5. $str |awk '{print length}' 

Note: Observe the quotation mark used around $string. If a string has spaces in it, then quotation mark are vital . Otherwise, it are often ignored. We recommend always use quotation mark around $string to get on the safe side.

The above syntax defines that we will find the length of a string with or without the bash command. Using '#' sign, we will calculate the length of a string without applying any bash command. Let's know it more clearly with the assistance of some examples:

Examples to seek out String Length in Bash

There are some examples given below illustrating the various ways to seek out a string length in bash shell scripting:

Example 1: in this script we will try to find the length of the string.

Code/ script:

#!/bin/bash  
#Bash program to find the length of a string  
  
str="Welcome to Great learning Academy"  
length=${#str}  
  
echo "Length of '$str' is $length" 

The Output of the above code.

Example 2: Another way to find the length of the given string.

#!/bin/bash  
#Bash script to find the length of a string  
  
str="Welcome to Great learning Academy blog"  
length=`echo $str |awk '{print length}'`  
  
echo "Length of '$str' is $length"