user3249696
user3249696

Reputation: 37

Bash show charcaters if not in string

I am trying out bash, and I am trying to make a simple hangman game now.

Everything is working but I don't understand how to do one thing:

I am showing the user the word with guessed letters (so for example is the world is hello world, and the user guessed the 'l' I show them **ll* ***l* )

I store the letters that the user already tried in var guess

I do that with the following:

echo "${word//[^[:space:]$guess]/*}"

The thing I want to do now is echo the alphabet, but leave out the letters that the user already tried, so in this case show the full alphabet without the L.

I already tried to do it the same way as I shown just yet, but it won't quite work.

If you need any more info please let me know.

Thanks, Tim

Upvotes: 1

Views: 78

Answers (2)

glenn jackman
glenn jackman

Reputation: 247012

You don't show what you tried, but parameter expansion works fine.

$ alphabet=abcdefghijklmnopqrstuvwxyz
$ word="hello world"
$ guesses=aetl
$ echo "${word//[^[:space:]$guesses]/*}"
*ell* ***l*
$ echo "${alphabet//[$guesses]/*}"
*bcd*fghijk*mnopqrs*uvwxyz

Upvotes: 1

ShellFish
ShellFish

Reputation: 4551

First store both strings in files where they are stored one char per line:

sed 's/./&\n/g' | sort <<< $guess > guessfile
sed 's/./&\n/g' | sort <<< $word > wordfile

Then we can filter the words that are only present in one of the files and paste the lines together as a string:

grep -xvf guessfile wordfile | paste -s -d'\0'

And of course we clean up after ourselves:

rm wordfile
rm guessfile

If the output is not correct, try switching arguments in grep (i.e. wordfile guessfile instead of guessfile wordfile).

Upvotes: 0

Related Questions