Bash – How to insert a string into a text variable at specified position

bashshellstring

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):

  1. Before the matched string, or
  2. 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 variable text at position p (counting from zero):

p=5
text="$(seq 10)"               ## arbitrary text
text="${text:0:p}j${text:p}"

To insert the text j before the matching portion in $match:

text="${text%%${match}*}j${match}${text##*${match}}"

This pulls off the leading portion of $text until it finds $match, then adds the j, then the $match, then the trailing portion of $text until it finds $match. Hopefully there's only one match of $match in $text!

Related Question