echo "/home/repository/tags/1.9.1/1.9.1.8/core" | sed "s/HELP/XXX/g"
我想要一些帮助来替换标签和核心之间的内容,让我们说XXX。所以我想要的输出是/ home / repository / tags / XXX / core。
字符串是目录路径,其中/ home / repository / tags是唯一的常量部分。路径总是六层深。所以它可能并不总是在标签和核心之间。
答案 0 :(得分:3)
echo "/home/repository/whatever/1.9.1/1.9.1.8/core/and/more/junk" \
| sed 's@\(/[^/]*/[^/]*/[^/]*\)/[^/]*/[^/]*@\1/XXX@'
收益......
/home/repository/whatever/XXX/core/and/more/junk
答案 1 :(得分:2)
通过使用重复量词,您可以轻松调整替换的位置:
echo "/home/repository/tags/1.9.1/1.9.1.8/core" | \
sed -r 's|(/([^/]+/){3})([^/]+/){2}(.*)|\1XXX/\4|'
你甚至可以使用变量:
$ dirs='/one/two/three/four/five/six/seven/eight'
$ for keep in {0..3}; do for replace in {0..3}; do echo "$dirs" | \
sed -r "s|(/([^/]+/){$keep})([^/]+/){$replace}(.*)|\1XXX/\4|"; done; done
/XXX/one/two/three/four/five/six/seven/eight
/XXX/two/three/four/five/six/seven/eight
/XXX/three/four/five/six/seven/eight
/XXX/four/five/six/seven/eight
/one/XXX/two/three/four/five/six/seven/eight
/one/XXX/three/four/five/six/seven/eight
/one/XXX/four/five/six/seven/eight
/one/XXX/five/six/seven/eight
/one/two/XXX/three/four/five/six/seven/eight
/one/two/XXX/four/five/six/seven/eight
/one/two/XXX/five/six/seven/eight
/one/two/XXX/six/seven/eight
/one/two/three/XXX/four/five/six/seven/eight
/one/two/three/XXX/five/six/seven/eight
/one/two/three/XXX/six/seven/eight
/one/two/three/XXX/seven/eight
答案 2 :(得分:1)
如果您的目录总是深度为6级,则可以使用(请记住转义圆括号):
echo "/home/repository/tags/1.9.1/1.9.1.8/core" |
sed 's/\(\/home\/repository\/tags\/\).*\/.*\(\/.*\)/\1XXX\2/'
产生
/home/repository/tags/XXX/core
答案 3 :(得分:0)
在这里,给自己留下一些正则表达式的痛苦:
echo "/home/repository/tags/1.9.1/1.9.1.8/core" | sed 's@/home/repository/tags/.*/\(.\+\)$@/home/repository/tags/XXX/\1@'
如果您真正想要做的就是删除tags/
和最后一个组件之间的所有内容,则无需明确匹配组件。请注意,我使用+
而非*
,因此组件必须为非空。这样可以防止出现斜线。