UNIX BASH replace char with dash w/o SED


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers UNIX BASH replace char with dash w/o SED
# 1  
Old 10-04-2011
UNIX BASH replace char with dash w/o SED

I am trying to create a script in UNIX BASH where I can change the string to dashes. This is part of a "hangman" game (not a homework assignment). Once the dashes are in place, I then need to add the letter to the new string (of dashes) based on where the letter is located. (ie The word is 'String' and I want to replace it with '------' and then once a user inputs a charater that matches, I want to replace it '----n-'.

Any help would be much appreaciated. I was able to get it to work with SED by doing the following:
Code:
Word="String"
read -p "Enter char: " char
chars="${chars}${char}
display=$(echo "$word" | sed "s/[^${chars}]/-/g")

BUT I need to get this same action done without useing SED.

I started using a for loop...
Code:
for (i=1;i<${#Word};i++)

But I am not sure where to go from here. Can anyone help me with this problem? I have the rest of the program working fine.

Thanks!

Last edited by vbe; 10-05-2011 at 11:17 AM.. Reason: please use code tags for your code/data
# 2  
Old 10-04-2011
Since this is BASH, you have many useful string operations available.

Code:
$ STR="abcdefghijklmnopqrstuvwxyz"
$ MATCH="ghi"
$ echo "${STR//[^${MATCH}]/-}"
------ghi-----------------
$

[edit] dash!? Bleh... I'll test...

---------- Post updated at 05:58 PM ---------- Previous update was at 05:51 PM ----------

No, it does not work with dash. dash isn't even as good as busybox(which that still works in), it doesn't have substring operators let alone character replacement. sed may be as good as anything.
# 3  
Old 10-04-2011
Thanks for the suggestion. I was not able to implement your suggestion into my coding. It may be due to the way I have my code set up. Here is the function I created:
Code:
function yesSelected()
{
local word=$(randomWord)
local count=0
local countChar=0
local correctWord="n"
local chars
local attempts=10
local display
local charLower




        clear
        while [[ $correctWord = "n" && $count -lt $attempts ]]
        do
        echo $word
        gameDisplay $count $countChar $display $chars
        echo
        read -p "Please enter a character: " char
        charLower=$(echo "$char" | tr [A-Z] [a-z] )
        (( countChar=countChar + 1 ))
        if [[ "$(letterValid $charLower)" -eq 0 ]]
        then
          if [[ $chars =~ .*$charLower.* ]]
          then
          clear
          charUsed
          else
            chars="${chars}${charLower}"
            if [[ $word =~ .*$charLower.* ]]
            then
                ((count = count))
              else
                ((count = count + 1))
            fi
              display=$(echo "$word" | sed "s/[^${chars}]/-/g")
            clear
            if [ $word = $display ]
            then
              correctWord="y"
              clear
            fi
          fi
        else
          clear
          invalidErrorMessage
        fi
        done
        if [[ $count -eq 10  ]]
        then
          echo "SORRY. The word was $word."
          echo
          tooManyAttempts
          echo
          gameEnded
          else
                congratsScreen
                gameEnded
          fi
}

yesSelected

I pass in a "randomWord" from another function and then use it to perform the task. I am trying not to use SED in my program so I wanted to see if there is another way to get the same result.

Thanks again for your help in this matter.

Last edited by vbe; 10-05-2011 at 11:21 AM..
# 4  
Old 10-04-2011
Quote:
Originally Posted by needsomehelp
sed "s/[^${chars}]/-/g")

BUT I need to get this same action done without useing SED.
Code:
tr -c "${chars}" '[-*]'

Regards,
Alister
# 5  
Old 10-04-2011
Thanks! That worked! I have used 'tr' before but I wasn't familiar using it in this manner. I was able to get my program going; however, when it echos to the screen, there is an extra dash for the random word (ie if the word is dog, it will have four dashes '----' and when I select d,o,g, the program thinks there is one additional character/dash.

Any thoughts why this might be doing this?

The line I have now is:
Code:
  display=$(echo "$word" | tr -c "${chars}" '[-*]')

I tried to enter a minus on the word but that didn't resolve the issue. I'm not sure why it is adding an extra character.

Last edited by vbe; 10-05-2011 at 11:20 AM..
# 6  
Old 10-05-2011
In addition to the value of $word, that echo statement is also outputting a newline character.

Personally, I hardly use echo these days. I'd use printf %s "$word", but you may prefer echo -n "$word".

By the way, I'm curious. Why are you not able to use sed?

Regards,
Alister
This User Gave Thanks to alister For This Post:
# 7  
Old 10-05-2011
I started messing around with a hangman game too for the fun of it after reading a posting here somewhere by Corona688 that gave an example on manipulating strings. It was a fun lunchtime project for a while but I haven't gotten back to it to fix a couple of bugs. It is playable though and may be useful to have a look at for the string manipulation techniques that Corona688 gave. So, here I go sticking my neck out again and put the code out there for example's sake.

It shows what letters have been called and attempts to draw the hangman (I'm no artist though lol). It looks like this when playing:

Code:
H A N G M A N

a cdefghijklmn pqrs uvwxz

   +---\-+
   |    \|
   O     |
  /      |
         |
         |
====================


  b_t_t_b

Enter a character, then ENTER:

It uses our Sun implementation of ksh93. Repeat: I realize it has bugs and is not complete and I am sure there are better ways to do some of the things I am doing. Flames > /dev/null but suggestions on improvement are always welcome as that is why we are all here in the first place! Let's have a little fun while learning something at the same time.

Code:
#!/usr/dt/bin/dtksh
##
##  Hangman exercise.  Built on sample code from Corona668 at unix.com
##

typeset l1="   +---\-+"
typeset l2="   |    \|"
typeset l3="         |"
typeset l4="         |"
typeset l5="         |"
typeset l6="         |"
set -f  l7="        /+\"
typeset l8="       /   \"
typeset l9="===================="

IFS=
alphabet="abcdefghijklmnopqrstuvwxzy"
letterused=" "
errs=0
foundit=0

WORD="bathtub"   # Need a function to randomly pick a word.

GUESS="${WORD//[a-z]/_}" # Replace all [a-z] with _

while [[ "$GUESS" != "$WORD" ]]
do
  in=""
  while [[ "${#in}" -ne 1 ]] || [[ ! -z "${in/[a-z]}" ]]
  do
    tput clear

    printf "H A N G M A N\n\n%s\n\n" $alphabet
    printf "%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n" $l1 $l2 $l3 $l4 $l5 $l6 $l7 $l8 $l9

    printf "  ${GUESS} \n\nEnter a character, then ENTER: "
    read in
  done

  # Loop through every character in $WORD, looking for the letter entered.
  for((i=0; i<${#WORD}; i++))
  do
    if [[ "${WORD:$i:1}" = "$in" ]]; then
      if [[ "${GUESS:$i:1}" = "$in" ]]; then
        print "You already guessed that!"
        sleep 1
        break;
      fi
      # i.e. replacing the first 't' in kitten.
      # ${GUESS:0:$i} gets 'ki'.
      # ${GUESS:$((i+1))} gets 'ten'.
      # We stick our guess, $in, in the middle.
      GUESS="${GUESS:0:$i}${in}${GUESS:$((i+1))}"
      foundit=1
    fi
  done
  if (( foundit )); then
    foundit=0
  else
    ((errs++))
    # Change the hangman pic to draw the man.  There must be a better way.
    case $errs in
      1) l3="${l3:0:3}O${l3:$((4))}"
         ;;
      2) l4="${l4:0:2}/${l4:$((3))}"
         ;;
      3) l4="${l4:0:3}#${l4:$((4))}"
         ;;
      4) l4="${l4:0:4}\\${l4:$((5))}"
         ;;
      5) l5="${l5:0:3}#${l5:$((4))}"
        ;;
      6) l6="${l6:0:2}/${l6:$((3))}"
         ;;
      7) l6="${l6:0:4}\\${l6:$((5))}"
         ;;
      *) break
         ;;
    esac
  fi
  # Remove the letter tried from the alphabet string.
  # Loop through every character in $alphabet.
  for((j=0; j<${#alphabet}; j++))
  do
    if [[ "${alphabet:$j:1}" = "$in" ]]; then
      alphabet="${alphabet:0:$j}${letterused}${alphabet:$((j+1))}"
    fi
  done
done

if (( errs > 6 ));then
  print "You lose; the word is $WORD\n"
else
  print "You got it!  $GUESS\n"
fi

 
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Advanced & Expert Users

Replace \n char in Data

File is pipe delimited with 17 fields. We may get \n char (1 or more \n in one field or multi fileds) in data in any field. Need to replace \n in data with space and not the Ture \n that is line separator. I tried below awk command it did not work as expected. awk '(NR-1)%2{$1=$1}1' RS=\|... (9 Replies)
Discussion started by: rajeshkumare
9 Replies

2. UNIX for Beginners Questions & Answers

Views How to replace a CRLF char from a variable length file in the middle of a string in UNIX?

My sample file is variable length, with out any field delimiters. It has min of 18 chars length and the 'CRLF' is potentially between 12-14 chars. How do I replace this with a space? I still want to keep end of record, but just want to remove these new lines chars in the middle of the data. ... (7 Replies)
Discussion started by: chandrath
7 Replies

3. Shell Programming and Scripting

Using sed command replace date variable in unix

I need to use a shell script, using sed command how to replace date variable value in following format. 04/18/2012 11:38:55 Because the sed is treating the '/' as a parameter instead of the value of a variable, and hence there is the message as sed: command garbled: s/insert/04/18/2012... (9 Replies)
Discussion started by: jannusuresh
9 Replies

4. UNIX for Dummies Questions & Answers

Bash: using SED, trying to replace some characters except first or last line

Hi, I require to replace 2 items: 1. replace start of all lines in a file with ' except the first line 2. replace end of all lines in a file with '||chr( except last line I am able to do the entire file using sed -e s/^/\'/g -e s/$/\'\|\|chr\(/g "$file" > newfile.txt but am not yet... (3 Replies)
Discussion started by: Chella15
3 Replies

5. Shell Programming and Scripting

Bash: using SED, trying to replace some characters except first or last line

Hi, I require to replace 2 items: 1. replace start of all lines in a file with ' except the first line 2. replace end of all lines in a file with '||chr( except last line I am able to do the entire file using sed -e s/^/\'/g -e s/$/\'\|\|chr\(/g "$file" > newfile.txt but am not yet able... (0 Replies)
Discussion started by: Chella15
0 Replies

6. Shell Programming and Scripting

Replace last row of a column in bash/awk/sed

Hi, I've got a file with 3 columns which ends like this: ... 1234 345 1400 5287 733 1400 8472 874 1400 9317 726 1400 I want to replace the last row of the last column with the value 0. So my new file will end: ... 1234 345 1400 5287 733 1400 8472 874 1400 9317 726 ... (5 Replies)
Discussion started by: jhunter87
5 Replies

7. Shell Programming and Scripting

Bash sed search and replace question

I have several files that I need to modify using sed. I know how to do that, but now a new requirement has come up. Now, I need to make changes to all lines that don't start with certain strings. For example, I need to change all lines except for lines that start with "a", "hello there",... (3 Replies)
Discussion started by: RickS
3 Replies

8. Shell Programming and Scripting

SED: Place char at starting and replace selected line

Hello Experts, I am working on a small file editing script. Since all experts here are very generous to give me the complete code, I would take up the problem in steps so that I ensure my opportunity to learn. AIM: The script has some commented and some uncommented lines. I need to : ... (2 Replies)
Discussion started by: hkansal
2 Replies

9. UNIX for Dummies Questions & Answers

Unix script, sed search and replace?

Hi, I am trying to write a shell script designed to take input line by line by line from a file with a word on each line for editing with sed. Example file: 1.ejverything 2.bllown 3.maikling 4.manegement 5.existjing 6.systems My design currently takes input from the user, and... (2 Replies)
Discussion started by: mkfitzwilliams
2 Replies

10. Shell Programming and Scripting

How to replace any char with newline char.

Hi, How to replace any character in a file with a newline character using sed .. Ex: To replace ',' with newline Input: abcd,efgh,ijkl,mnop Output: abcd efgh ijkl mnop Thnx in advance. Regards, Sasidhar (5 Replies)
Discussion started by: mightysam
5 Replies
Login or Register to Ask a Question