小编Naz*_*zar的帖子

如何将字符串插入到指定位置的文本变量中

我找到了很多字符串操作教程,但无法弄清楚如何将它们应用于我的特定情况。我需要使用任一方法将字符串变量word插入(而不是替换)到文本变量text 中(不能依赖于行编号,变量操作优先于读/写文件):

  1. 在匹配的字符串之前,或
  2. 在特定索引处(字节位置)

    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"
    
    Run Code Online (Sandbox Code Playgroud)

请帮助找出语法。修复这两种方法会很好。还有其他方法吗?的文本含有>文本的1MB,这样,有效的方法是优选的。

shell bash string

7
推荐指数
1
解决办法
4万
查看次数

标签 统计

bash ×1

shell ×1

string ×1