Manipulate strings in shell scripts

To manipulate strings in shell scripts, you can use a number of operations and commands available in the language. Some examples of how to find and replace text in a string are:

Finding text in a string: You can use the “grep” command to find a pattern of text in a string. For example, the following command looks for the word “example” in the string “This is an example string”:

echo “This is an example string” | grep example

The result would be “example string”.

Replace text in a string: You can use the “sed” command to replace a text pattern in a string. For example, the following command replaces the word “example” with “test” in the string “This is an example string”:

echo “This is an example string” | sed ‘s/example/test/g’

The result would be “This is a test string”.

Get the length of a string: You can use the “#” operator to get the length of a string. For example, the following command returns the length of the string “example”:

string=”example”
echo “${#string}”

The result would be “7”.

Replacing the contents of a variable: You can use the “=” operator to replace the contents of a variable. For example, the following command replaces the contents of the “string” variable from “example” to “test”:

string=”example”
string=”test”
echo “$string”

The result would be “test”.

Extract a substring: You can use the “cut” command to extract a part of a string. For example, the following command extracts the first two characters from the string “example”:

echo “example” | cut -c 1-2

The result would be “ex”.