【问题标题】:How to match string between two delimiters and append a string after如何匹配两个分隔符之间的字符串并在后面附加一个字符串
【发布时间】:2019-12-04 08:20:48
【问题描述】:

我有一个文件,内容如下:

[idx1]
path1 = $test/idx1/test
path2 = $test/idx1/test
path3 = $test/idx1/test

[idx2]
path1 = $test/idx2/test
path2 = $test/idx2/test
path3 = $test/idx2/test

有没有办法在分隔符之间匹配 idx1、idx2 等所有字符串,并在每次匹配后附加一个字符串。

[idx1_string]
path1 = $test/idx1_string/test
path2 = $test/idx1_string/test
path3 = $test/idx1_string/test

[idx2]
path1 = $test/idx2_string/test
path2 = $test/idx2_string/test
path3 = $test/idx2_string/test

【问题讨论】:

  • 也许echo "path2 = $test/idx2/test" | awk -F/ '{$2=$2"_string"}1' 会给你一个想法。祝你好运。
  • 当你在[idx1] 之后有_string (第二段)时,为什么不在_string 之后呢?

标签: bash shell awk sed scripting


【解决方案1】:

将实现您的目标的sed 的简单扩展正则表达式是:

sed -r 's/idx(\w+)/idx\1_string/' file

表达式使用匹配 \w 的单词匹配 [a-zA-Z0-9]

要就地编辑文件,请添加-i 作为选项,并在就地编辑时保留带有.bak 扩展名的原始副本,只需将选项添加为-i.bak

使用/输出示例

使用您的输入文件,示例使用和输出将是:

$ sed -r 's/idx(\w+)/idx\1_string/' file
[idx1_string]
path1 = $test/idx1_string/test
path2 = $test/idx1_string/test
path3 = $test/idx1_string/test

[idx2_string]
path1 = $test/idx2_string/test
path2 = $test/idx2_string/test
path3 = $test/idx2_string/test

【讨论】:

  • 如果字符串 idx 在整个文件中不一致怎么办?我可以做这样的事情吗? sed -r 's/[(\w+)]|\/(\w+)\//_string/' 测试文件
  • 如何引用捕获组?
  • 当您引用一个捕获组时,您使用的是反向引用。因此,如果您有两个捕获组,请分别使用 \1\2 引用它们。因此,根据您的评论,您将执行sed -r 's/[(\w+)]|\/(\w+)\//\1\2/' testfile(在...\1...\2... 之前、之间或之后添加您需要的任何内容)
【解决方案2】:

如果你想改变一切

sed -r 's/(idx[0-9])/\1_string/' file
[idx1_string]
path1 = $test/idx1_string/test
path2 = $test/idx1_string/test
path3 = $test/idx1_string/test

[idx2_string]
path1 = $test/idx2_string/test
path2 = $test/idx2_string/test
path3 = $test/idx2_string/test

如果不应该更改标题。

sed -r 's|(idx[0-9])/|\1_string/|' file
[idx1]
path1 = $test/idx1_string/test
path2 = $test/idx1_string/test
path3 = $test/idx1_string/test

[idx2]
path1 = $test/idx2_string/test
path2 = $test/idx2_string/test
path3 = $test/idx2_string/test

【讨论】:

    【解决方案3】:

    您的问题不清楚,但您似乎可能询问如何执行以下任一操作:

    $ sed 's:/\([^/]*\)/:/\1_string/:' file
    [idx1]
    path1 = $test/idx1_string/test
    path2 = $test/idx1_string/test
    path3 = $test/idx1_string/test
    
    [idx2]
    path1 = $test/idx2_string/test
    path2 = $test/idx2_string/test
    path3 = $test/idx2_string/test
    
    $ sed 's:\([[/]\)\([^/]*\)\([]/]\):\1\2_string\3:' file
    [idx1_string]
    path1 = $test/idx1_string/test
    path2 = $test/idx1_string/test
    path3 = $test/idx1_string/test
    
    [idx2_string]
    path1 = $test/idx2_string/test
    path2 = $test/idx2_string/test
    path3 = $test/idx2_string/test
    

    【讨论】:

      猜你喜欢
      • 2019-04-05
      • 1970-01-01
      • 2012-04-27
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多