在bash中转换字符串 - 在params周围添加括号

时间:2018-01-30 11:55:28

标签: bash perl awk sed

我尝试了以下sed,但无法解决如何停止正斜线多次应用

sed 's/(.*):([^:]*)/\1{\2}/g' 

我的输入看起来像

/resource/:paramName
/resource/:paramName/another-resource
/resource/:paramName/another-resource/:anotherParam/final-resource
/resource/:aParam/another-resource/:differentParam/final-resource

分为:

/resource/{paramName}
/resource/{paramName}/another-resource
/resource/{paramName}/another-resource/{anotherParam}/final-resource
/resource/{aParam}/another-resource/{differentParam}/final-resource

1 个答案:

答案 0 :(得分:4)

使用GNU awk

awk '{print gensub(/:([^/]*)/,"{\\1}","g")}' file

其他awk

awk '{gsub(/:[^/]*/,"{&}"); gsub(/{:/,"{")}1' file

<强> 桑达

sed  -r 's/:([^/]*)/{\1}/g' file

测试结果:

$ cat file
/resource/:paramName
/resource/:paramName/another-resource
/resource/:paramName/another-resource/:anotherParam/final-resource
/resource/:aParam/another-resource/:differentParam/final-resource

GNU awk

$ awk '{print gensub(/:([^/]*)/,"{\\1}","g")}' file
/resource/{paramName}
/resource/{paramName}/another-resource
/resource/{paramName}/another-resource/{anotherParam}/final-resource
/resource/{aParam}/another-resource/{differentParam}/final-resource

其他awk:

$ awk '{gsub(/:[^/]*/,"{&}"); gsub(/{:/,"{")}1' file
/resource/{paramName}
/resource/{paramName}/another-resource
/resource/{paramName}/another-resource/{anotherParam}/final-resource
/resource/{aParam}/another-resource/{differentParam}/final-resource

Sed:

$ sed  -r 's/:([^/]*)/{\1}/g' file 
/resource/{paramName}
/resource/{paramName}/another-resource
/resource/{paramName}/another-resource/{anotherParam}/final-resource
/resource/{aParam}/another-resource/{differentParam}/final-resource