Debug School

rakesh kumar
rakesh kumar

Posted on

Bash String

Bash String

Bash Find

Bash Split String

Bash Substring

Bash Concatenate String

==============================

Bash String

Equal Operator
Not Equal Operator
Less than Operator
Greater than Operator
To check if the string length is greater than Zero:
([ -n Operand ])
To check if the string length is equal to Zero
([ -z Operand ])

Bash Find

Bash StringLength
expr length "$string"
expr "$string" :'.*'
$str | wc -c

$str |awk '{print length}'

Bash Split String

Split using $IFS variable
Bash Split String by Space
Bash Split String by Symbol
Split without $IFS variable
Bash Split String by Symbol
Bash Split String by Symbol

Bash Substring

${variable:offset:length}

To Extract till Specific Characters from Starting
${str:0:10}"
To Extract from Specific Character onwards
${str:11}
To Extract a Single Character
${str:11:1}
To Extract the specific characters from last
${str:(-11)}

Bash Concatenate String

Write Variables Side by Side
$str1$str2
Using Double Quotes
"$str on Javatpoint."
Using Append Operator with Loop
lang+="$value "
Using the Printf Function
printf -v new_str "$str to Javatpoint."
Using Literal Strings
newstr="${str} Javatpoint."

Using Underscore
"${str1}_${str2}"

Using any Character
combine="$name,$state,$age"

In this topic, we have demonstrated about bash string and its operators.

Like other programming languages, Bash String is a data type such as as an integer or floating-point unit. It is used to represent text rather than numbers. It is a combination of a set of characters that may also contain numbers.

For example, the word "javatpoint" and the phrase "Welcome to javatpoint" are the strings. Even "01234" could be considered as a string, if specified correctly. Programmers are required to enclose strings in quotation marks for the data to be considered as a string and not a number, variable name or array, etc.

Bash consists of multiple ways to perform string operations and manipulate them.

Following are some operators in Shell Script used to perform string operations:

Equal Operator
An equal operator (=) is used to check whether two strings are equal.

Syntax

Operand1 = Operand2  
Enter fullscreen mode Exit fullscreen mode

Example

!/bin/bash

Script to check whether two strings are equal.

str1="WelcometoJavatpoint."  
str2="javatpoint"  

if [ $str1 = $str2 ];  
then  
echo "Both the strings are equal."  
else  
echo "Strings are not equal."  
fi  
Enter fullscreen mode Exit fullscreen mode

Output

Strings are not equal.
Enter fullscreen mode Exit fullscreen mode

Not Equal Operator
Not equal operator (!=) is used to define that strings are not equal.

Syntax

Operand1 != Operand2  
Enter fullscreen mode Exit fullscreen mode

Example

#!/bin/bash  
#Script to check whether two strings are equal.  

str1="WelcometoJavatpoint."  
str2="javatpoint"  

if [[ $str1 != $str2 ]];  
then  
echo "Strings are not equal."  
else  
echo "Strings are equal."  
fi 
Enter fullscreen mode Exit fullscreen mode

Output

Strings are not equal.
Enter fullscreen mode Exit fullscreen mode

Less than Operator
The 'less than operator (<)' is a conditional operator which is used to check if string1 is less than string2.

Syntax

Operand1 \< Operand2  
Enter fullscreen mode Exit fullscreen mode

Example

#!/bin/sh   

str1="WelcometoJavatpoint"  
str2="Javatpoint"  
if [ $str1 \< $str2 ];  
then   
    echo "$str1 is less then $str2"  
else  
    echo "$str1 is not less then $str2"  
fi 
Enter fullscreen mode Exit fullscreen mode

Output

WelcometoJavatpoint is not less then Javatpoint
Enter fullscreen mode Exit fullscreen mode

Greater than Operator
The 'greater than operator (>)` is used to check if string1 is greater than string2.

Syntax


Operand1 \> Operand2

Example

Image description

Image description

Image description

Image description

Image description

Image description

Bash Find

n this topic, we have 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 might need to know about the length of a string to perform some specific tasks. Most of the programming languages have their own built-in functions to calculate the number of characters. However, Bash does not contain such type of built-in functions. But there are several ways that we can use to find the length of a string in Bash Scripting.

Bash StringLength
To calculate the length of a string, we can use any of the following syntax:

  1. ${#string}
  2. expr length "$string"
  3. expr "$string" :'.*'
  4. $str | wc -c
  5. $str |awk '{print length}' Note: Observe the double quotes used around $string. If a string has spaces in it, then double quotes are very important. Otherwise, it can be ignored. We recommend to always use double quotes around $string to be on the safe side. The above syntax defines that we can find the length of a string with or without bash command. Using '#' sign, we can calculate the length of a string without applying any bash command. Let's understand it more clearly with the help of some examples:

Examples to find String Length in Bash
There are some examples given below illustrating the different ways to find a string length in bash shell scripting:

Example 1

The simplest way to calculate the length of a string is to use '#' symbol. In this example, we have used $[#string_variable_name} to find the length of a string.

`

Image description

Image description

Image description

Image description

Image description

Bash Split String

In this topic, we have defined how to split a string in bash shell scripting.

In some cases, we might need to split the string data to perform some specific tasks. Most of the programming languages contain built-in function 'split' to divide any string data into multiple parts. However, bash does not contain such type of built-in function. But we can use delimiters to split any string data in bash scripting. The delimiter can be either a single character or a string with multiple characters.

Check out the methods below to understand how to split string in a bash shell:

Split using $IFS variable
Following are the steps to split a string in bash using $IFS:

  1. $IFS is a special internal variable which is used to split a string into words. $IFS variable is called 'Internal Field Separator' which determines how Bash recognizes boundaries. $IFS is used to assign the specific delimiter [ IFS='' ] for dividing the string. The white space is a default value of $IFS. However, we can also use values such as '\t', '\n', '-' etc. as the delimiter.
  2. After assigning the delimiter, a string can be read by two options: '-r' and '-a'. i.e., read -ra ARR <<< "$str".
  3. Here, the option '-r' is used to define that backslash () is a character rather than escape character. The '-a' option is used to define that the words (separated by $IFS) are assigned to the sequential index of array beginning at zero.
  4. Then we apply bash 'for' loop to access the tokens which are split into an array. Let's understand this mechanism with the help of some examples:

Example 1: Bash Split String by Space
In this example, a string is split using a space character delimiter.

Image description

Image description

Image description

Image description

Split without $IFS variable
In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

Let's understand this logic with the help of some example:

Example 1: Bash Split String by Symbol
This example defines how a string value can be split without using $IFS. As per the script, a text value should be entered with the colon (:) sign so that it can be split. Check out the bash script below:

Image description

Image description

Image description

Image description

Image description

Image description

Bash Substring

In this topic, we have explained how to compute substring of a given string.

A substring is a sequence of characters within a string. Bash provides an option to extract the information from a string itself. You can extract the digits or a given string using several methods.

For example, "welcome you on Javatpoint." is a substring of "We welcome you on Javatpoint."

Syntax
The command for the extraction of substring is a build-in bash command, and so it is very good to use for performance perspective.

The syntax of the substring extraction can be defined as:

`
${variable:offset:length}
`

where,

Variable is the variable name that contains a string.
Offset is used to specify the position from where to start the extraction of a string.
Length is used to specify the range of the characters to be executed from the offset.

Note: Assigning length is optional. If length is not provided, then end of the string will be considered as the end of the substring.
Let's understand the concept of extracting a substring from the string with the help of some examples:

Example 1: To Extract till Specific Characters from Starting

Image description

Image description

Image description

Image description

Image description

Bash Concatenate String

In this topic, we have explained how to add or concatenate strings in Bash Shell Scripting.

In bash scripting, we can add or join two or more strings together, which is known as string concatenation. It is one of the common requirement for any programming language. A special character or built-in function is applied to perform string concatenation. However, Bash does not contain any built-in function to combine string data or variables. The easiest method to perform string concatenation in bash is to write variables side by side.

For example, assume that we have two strings (i.e., "welcome" & "to javatpoint"), and we join both the strings together and a new string ("welcome to javatpoint") is created. This concept is referred to as String Concatenation.

Command
The example command for concatenating the strings can be defined as:

`
str3="$str1$str2"
`

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Image description

Top comments (0)