JIYIK CN >

Current Location:Home > Learning > OPERATING SYSTEM >

Replace characters in a string using Bash

Author:JIYIK Last Updated:2025/04/15 Views:

A common operation involving string literals is replacing individual characters or substrings within the string with other characters or substrings.

In this article, we will look at several ways to do string replacement using the BASH shell.


Method 1 – Using tr Command

tr is a very handy Bash command that can be used to perform different transformations on strings. It is particularly useful in string transformations (for example, changing the case of a string to upper or lower case), removing substring duplications, and searching and replacing substrings.

It is used to replace characters and substrings in a string.

syntax:

echo "$variableName" | tr [character(s)ToBeRemoved] [character(s)ToBeAdded]

Script example:

STR="ABCD"
echo "$STR" | tr A Z

Output:

ZBCD

The character ‘A’ in the string variable $STRis replaced with the character ‘Z’. It is important to note that the above command also works to replace all instances of the character ‘A’.

Script example:

STR="ABACAD"
echo "$STR" | tr A Z

Output:

ZBZCZD

For more complex use cases, such as replacing a single character with multiple characters or replacing a substring with another substring, you can still use trthe command, but it will be necessary to incorporate and use regular expressions (RegEx) to accomplish such tasks.

trAnother useful command option is the squeeze or -s option, which replaces a range of characters or a substring with a single character.

Script example:

STR="ABBBCDDDDDE"
echo "$STR" | tr -s BD Z

Output:

AZCZE

It can be seen that multiple adjacent occurrences of the characters "B" and "D" are replaced by a single "Z".


Method 2 - Using Bash Parameter Expansion

The $ sign is usually preceded by a variable name and is used to assign a value to the variable or print its contents. However, we can also use it for parameter expansion.

We can use parameter expansion to replace the contents of a variable with a given substring in the following way.

syntax:

${varName/substring/replacement}

Note, for variable expansion, the use of curly braces is optional.

Script example:

STR="I LIKE FOOTBALL"
echo ${STR/FOOTBALL/CRICKET}

Output:

I LIKE CRICKET

Note, use a single forward slash after the variable name in the parameter expansion command to replace only the first occurrence of a substring. Use the following script to replace all occurrences of a substring within a string or double forward slashes.

Script example:

${varName//substring/replacement}

Method 3 – Using sed Command

sedThe sed command is similar to the tr command. Nonetheless, it is more powerful as it can be used to directly edit text files without opening them. The sed command in BASH stands for stream editor. It performs many functions on files such as searching, find and replace, and insert or delete.

sedThe command can be used for string replacement in the following ways.

Script example:

STR=AZC
echo "$STR" | sed -r 's/[Z]+/B/g'

Output:

ABC

This is similar to using the -rtr option after the command. The -r option sedafter the command stands for replace, and the pattern match (RegEx) describes what to find and replace.

Note, The syntax of the command differs slightly between versions of bash on different systems , sedwhich may cause unpredictable behavior.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to decompress x.tar.xz format files under Linux

Publish Date:2025/04/08 Views:186 Category:OPERATING SYSTEM

A lot of software found today is in the tar.xz format, which is a lossless data compression file format that uses the LZMA compression algorithm. Like gzip and bzip2, it supports multiple file compression, but the convention is not to compr

Summary of vim common commands

Publish Date:2025/04/08 Views:115 Category:OPERATING SYSTEM

In Linux, the best editor should be vim. However, the complex commands behind vim's powerful functions also make us daunted. Of course, these commands do not need to be memorized by rote. As long as you practice using vim more, you can reme

Detailed explanation of command return value $? in Linux

Publish Date:2025/04/08 Views:58 Category:OPERATING SYSTEM

? is a special variable. This variable represents the return value of the previous command. That is to say, when we run certain commands, these commands will return a code after running. Generally, if the command is successfully run, the re

Common judgment formulas for Linux script shell

Publish Date:2025/04/08 Views:159 Category:OPERATING SYSTEM

In shell script programming, predicates are often used. There are two ways to use predicates, one is to use test, and the other is to use []. Let's take a look at how to use these two methods through two simple examples. Example 1 # test –

How to use the Linux file remote copy command scp

Publish Date:2025/04/08 Views:151 Category:OPERATING SYSTEM

Scp copies files between two hosts over the network, and the data is encrypted during transmission. Its underlying layer uses ssh for data transmission. And it has the same authentication mechanism and the same security level as ssh. When u

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial