konsolebox |
03-13-2008 09:32 PM |
thanks to your request i got fun again writing these new scripts :)
(a)
Code:
#!/bin/bash
echo -n "input new string with numbers: "
read string
# get the digits, there are many ways to do this
digits=$(echo -n "$string" | sed 's/[^1-9]//g')
# count the number of digits
dcount=$(echo -n "$digits" | wc -c)
# check digit count
if [[ dcount -eq 0 ]]; then
echo "there where no digit found in the string"
exit 1
fi
# print the digits
echo "digits found: $digits"
# ask for a replacement
until echo -n "please enter a $dcount digit number to replace the digits: ";
read rdigits;
[ ${#rdigits} -eq $dcount ] && [[ $rdigits =~ ^[[:digit:]]+$ ]]; do
echo "that's not a 3 digit number!"
done
# split the strings to arrays
stringarray=( $(echo "$string" | sed 's/./& /g') )
rdigitsarray=( $(echo "$rdigits" | sed 's/./& /g') )
# print
rpos=0
for a in ${stringarray[*]}; do
if [[ $a =~ [[:digit:]] ]]; then
echo -n ${rdigitsarray[b++]}
else
echo -n ${a}
fi
done
echo
(b)
Code:
#!/bin/bash
until
# ask for strings
echo -n "input new string with numbers: "
read string
# get the digits, there are many ways to do this
digits=$(echo -n "$string" | sed 's/[^0-9]//g')
# count the number of digits
dcount=$(echo -n "$digits" | wc -c)
# check digit count
[[ dcount -gt 0 ]]; do
echo "there where no digit found in the string"
done
# print the digits
echo "digits found: $digits"
# ask for a replacement
until echo -n "please enter a number to replace the digits: ";
read rdigits;
[ ${#rdigits} -gt 0 ] && [[ $rdigits =~ ^[[:digit:]]+$ ]]; do
echo "that's not a number!"
done
# split the strings to arrays
stringarray=( $(echo "$string" | sed 's/./& /g') )
rdigitsarray=( $(echo "$rdigits" | sed 's/./& /g') )
# print
rpos=0
rcount=${#rdigitsarray[@]}
spos=0
scount=${#stringarray[@]}
while [[ spos -lt scount && rpos -lt rcount && rpos -lt dcount ]]; do
if s=${stringarray[spos++]}; [[ ${s} =~ [[:digit:]] ]]; then
echo -n "${rdigitsarray[rpos++]}"
else
echo -n "${s}"
fi
done
while [[ spos -lt scount ]]; do
echo -n "${stringarray[spos++]}"
done
while [[ rpos -lt rcount ]]; do
echo -n "${rdigitsarray[rpos++]}"
done
echo
The first code is strict to the actual number of digits you put in the first string
For the second one, as long as you enter a number to replace the string, it will use it.
hope this can help
regards
Edit:
btw if you want to append the extra digits of the replace string to the last digit of the first string instead of the last character, you just have to reverse the last parts of the code to:
Code:
while [[ rpos -lt rcount ]]; do
echo -n "${rdigitsarray[rpos++]}"
done
while [[ spos -lt scount ]]; do
echo -n "${stringarray[spos++]}"
done
|