How to insert string using Bash

Shell Scripting

To insert string into another string, it is necessary to split the string into two parts—the part that will be to the left of the inserted string and the part to the right. Then the insertion string is sandwiched

between them.

This function takes three arguments: the main string, the string to be inserted, and the position at which to insert it. If the position is omitted, it defaults to inserting after the first character. The work is

done by the first function, which stores the result in _insert_string. This function can be called to save

the cost of using command substitution. The insert_string function takes the same arguments, which it passes to _insert_string and then prints the result (Listing 1).

Listing 1. insert_string, Insert One String into Another at a Specified Location

_insert_string() #@ USAGE: _insert_string STRING INSERTION [POSITION]


local insert_string_dflt=2    ## default insert location local string=$1    ## container string

local i_string=$2    ## string to be inserted

local i_pos=${3:-${insert_string_dflt:-2}} ## insert location

local left right    ## before and after strings left=${string:0:$(( $i_pos – 1 ))}    ## string to left of insert

right=${string:$(( $i_pos – 1 ))}    ## string to right of insert

_insert_string=$left$i_string$right    ## build new string




_insert_string “[email protected]” && printf “%s\n” “$_insert_string”



$ insert_string poplar u 4 popular

$ insert_string show ad 3


$ insert_string tail ops ## use default position topsail

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.