Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how use position for replace a letter

Tags:

bash

debian

code :

#!/bin/bash
word=$( sort -R $2 | head -1 | tr [a-z] [A-Z])
cache=$( echo $word | tr [A-Z] '_')
nb=$( echo $word | wc -m)
nbCar=$( echo $nb -1| bc)
echo "Mystery word: $cache ($nbCar letters)"
echo $word
echo "Enter a letter:"
read -n 1 letter
echo ""
pos=$( echo $word | grep -aob ${letter^^} | grep -oE '[0-9]+')
echo ${letter^^}
echo $pos

so how with my var $pos i can replace cache '_' by the letter read

example1: my word is yoyo

i read y

$pos = 0 2    
cache = y_y_

example2: my word is yoyo

i read a

$pos = NULL
cache = ____

echo "Not found"

like image 997
NoRage Avatar asked Jul 07 '26 05:07

NoRage


1 Answers

You could use two different approaches:

  1. to read the string in the position you want

    echo ${word:$pos:1}

You'll echo one character from word in the position $pos

  1. to write the string in the position you want

echo $word | sed "s/./<The character that you want>/$pos"

The " are important as you are putting a $pos (with only ' it would fail)

As you have multiple positions in your $pos, you'll have to iterate and change one at a time.

Interesting Links

  • https://www.tldp.org/LDP/abs/html/string-manipulation.html

  • Change string char at index X

like image 160
jmartori Avatar answered Jul 10 '26 13:07

jmartori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!