I found many string manipulation tutorials, but can not figure out how to apply them to my particular situation. I need to insert (not substitute) a string variable word into a text variable text using either method (can not depend on line numbering, variable manipulation preferred over read/write to a file):
- Before the matched string, or
-
At a specific index (byte position)
text="mytextMATCHmytext" word="WORD" match="MATCH" # method1 - not working, because text is not a file sed '/$word/ i $match' text # method2 indx="${text%%$match*}" indx=${indx%:*} # leave only the byte index where match starts text="$text{0-$index-1}$word$text{$index-end}" # expected value of text: "mytextWORDMATCHmytext"
Please, help to figure out the syntax. It would be nice to fix both methods. Any other ways of doing it? The text contains >1MB of text, so, the efficient way is preferred.
Best Answer
To insert the text
j
into the variabletext
at positionp
(counting from zero):To insert the text
j
before the matching portion in$match
:This pulls off the leading portion of
$text
until it finds$match
, then adds thej
, then the$match
, then the trailing portion of$text
until it finds$match
. Hopefully there's only one match of$match
in$text
!