4

I want to generate riddles from accordingly formatted input strings.

Example input: Foo was the +first+ to get a drink at +the bar+.

Desired output: Foo was the _____ to get a drink at ___ ___.

With any standard shell tool, what's the simplest (on the eye) solution for this?

user569825
  • 2,369
  • 1
  • 25
  • 45

3 Answers3

5

This awk one-liner should help you:

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

Test

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 ___ ___.
Kent
  • 189,393
  • 32
  • 233
  • 301
  • This is actually nicer than mine for sure and easier on the eye. As an aside: Though unspecified in the question (and probably completely irrelevant here) but yours and mine give different output for edge cases and malformed strings, such as "X++Y" and "X+++Y". – fastcatch Apr 28 '16 at 21:05
  • What is the purpose of `7` at the end? Without it, no output prints but I couldn't understand its purpose. – Utku May 02 '16 at 08:10
  • 1
    @Utku non-zero number will do default action : print in awk. 7, 1, 100, 1000 in this case do the same – Kent May 02 '16 at 08:27
1

Your "easy on the eye" test may get ... strained by the answers to this question.

Perl:

$ echo "$str" | perl -pe 's/\+(.*?)\+/ ($new=$1) =~ s{\w}{_}g; $new /eg'
Foo was the _____ to get a drink at ___ ___.
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

This works but ain't especially pretty:

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'

like this:

$ 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 ____ ____.

Basicly 'stolen' from here: https://stackoverflow.com/a/16014707/1061997

Community
  • 1
  • 1
fastcatch
  • 755
  • 6
  • 18