sed 替换由用户定义的分隔符划分的未知字符串的位置匹配 [英] sed replace positional match of unknown string divided by user-defined separator
本文介绍了sed 替换由用户定义的分隔符划分的未知字符串的位置匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想要从字符串重命名(未知)文件路径中的(已知)第 3 个文件夹,当位于第 3 级且分隔符为/
Want to rename the (known) 3th folder within a (unknown) file path from a string, when positioned on 3th level while separator is /
sed 需要一个明确的单行.因为我以后想用它来做 tar --transform=EXPRESSION
Need a one-liner explicitly for sed. Because i later want use it for tar --transform=EXPRESSION
string="/db/foo/db/bar/db/folder"
echo -e "$string" | sed 's,db,databases,'
sed 仅在第 3 级替换db"
sed replace "db" only on 3th level
预期结果
/db/foo/databases/bar/db/folder
推荐答案
您可以使用捕获组来捕获 /db/foo/
然后匹配 db
.然后在使用 \1
的替换中使用使用第一个捕获组:
You could use a capturing group to capture /db/foo/
and then match db
. Then use use the first caputring group in the replacement using \1
:
string="/db/foo/db/bar/db/folder"
echo -e "$string" | sed 's,^\(/[^/]*/[^/]*/\)db,\1databases,'
关于模式
^
字符串开始\(
开始捕获组/[^/]*/[^/]*/
使用否定字符类匹配前 2 个部分
^
Start of string\(
Start capture group/[^/]*/[^/]*/
Match the first 2 parts using a negated character class
那会给你
/db/foo/databases/bar/db/folder
这篇关于sed 替换由用户定义的分隔符划分的未知字符串的位置匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文