A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/linux-unix/bash-scripting-string/ below:

Bash Scripting - String - GeeksforGeeks

Bash Scripting - String

Last Updated : 01 May, 2022

Bash String is a data type similar to integer or boolean. It is generally used to represent text. It is a string of characters that may also contain numbers enclosed within double or single quotes. 

Example:  "geeksforgeeks", "Geeks for Geeks" or "23690" are strings

Creating a String

A basic declaration and assignment of string

str1="GeeksforGeeks"
str2=geeksforgeeks

The quotes can be omitted, but there shouldn't be any space before and after the equals operator

Example
#!/bin/bash  
#Initializing the strings
 
string1="GeekForGeeks"
string2='Geeks for Geeks'
string3=2345656778

#Printing the strings

echo $string1
echo $string2
echo $string3
Output   Reading the string from the user

The input can be read from the user using the read command.

Example
#!/bin/bash

echo What is your name
read name
echo "Hello there, $name"
Output   Concatenation of Strings

Strings in bash can be easily concatenated by listing the strings in order.

Example
#!/bin/bash
s1="Geeks"
s2="for"
s3="Geeks"
s4=${s1}${s2}${s3};
echo ${s4};
Output   Length of the String

The length of a given string can be accessed using the # operator by placing it inside the parameter expansion (curly braces) before the variable name.

Example
#!/bin/bash
string="geeksforgeeks"
echo "The length of the string is : ${#string}"
Output   String Replacement

Parts of an existing string can be replaced using  /  inside the parameter expansion. The syntax is given below.

${<variable_name>/<string_to_replace>/<new_string>}

This will replace the specified string with the new string once.

Example
string="Hello, Geeks!"
echo "String before replacement ${string}"
echo "String after replacement ${string/Geeks/World}"
Output  

To replace every single matched string from the existing string, two slashes are used '//' after the variable name, so it becomes.

${<variable_name>//<string_to_replace>/<new_string>}

Let us replace all the instances of the word butter from the below phrase.

Betty brought a bit of butter
but the butter was bit of bitter
so she brought some better butter
to make the bitter butter better

#!/bin/bash

para="Betty brought a bit of butter but the butter was bit of bitter so she brought some better butter to make the bitter butter better"

#This will replace every instance of butter in the phrase to BATTER

echo "${para//butter/BATTER}"

Output  

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4