如何非贪婪地替换一行的多个分隔字符串?

时间:2016-04-28 18:57:46

标签: awk sed grep

我想从相应格式化的输入字符串生成谜语。

示例输入: Foo was the +first+ to get a drink at +the bar+.

期望的输出: Foo was the _____ to get a drink at ___ ___.

使用任何标准的shell工具,最简单的(在眼睛上)解决方案是什么?

3 个答案:

答案 0 :(得分:5)

这个awk单行应该可以帮到你:

awk -F'+' -v OFS="" 'NF>2{for(i=2;i<=NF;i+=2)gsub(/\S/,"_",$i)}7'

测试

kent$  awk -F'+' -v OFS="" 'NF>2{for(i=2;i<=NF;i+=2)gsub(/\S/,"_",$i)}7' <<<"Foo was the +first+ to get a drink at +the bar+."
Foo was the _____ to get a drink at ___ ___.

答案 1 :(得分:1)

你的“轻松上眼”测试可能会因为这个问题的答案而变得紧张。

的Perl:

$ echo "$str" | perl -pe 's/\+(.*?)\+/ ($new=$1) =~ s{\w}{_}g; $new /eg'
Foo was the _____ to get a drink at ___ ___.

答案 2 :(得分:0)

这可行,但特别漂亮:

sed -r ':a;/\+[^+]*\+/!b;s//\n&\n/;h;s/.*\n(.*)\n.*/\1/;s/\+([^+]*)\+/\1/g;s/[^ ]/_/g;G;s/(.*)\n(.*)\n.*\n/\2\1/;ta'
像这样:

$ echo "Foo was the +first+ to get a drink at +the bar+." | sed -r ':a;/\+[^+]*\+/!b;s//\n&\n/;h;s/.*\n(.*)\n.*/\1/;s/\+([^+]*)\+/\1/g;s/[^ ]/_/g;G;s/(.*)\n(.*)\n.*\n/\2\1/;ta'
Foo was the _______ to get a drink at ____ ____.

基本上被盗&#39;从这里:https://stackoverflow.com/a/16014707/1061997

相关问题