Home > Software engineering >  how to increment all digits in string(Bash Script)
how to increment all digits in string(Bash Script)

Time:04-08

My code

#!/bin/bash
echo -n "Zadaj vetu: "
read str
echo $str | awk '{ for (i=NF; i>1; i--) printf("%s ",$i); print $1; }' | tr ' ' '\n' | tr -d '#' | tr -d '=' | tr -d '-' 

I need help, I don't understand how to make all the digits in the string that we thought to increase by one. (If there are 9 we should do 0)

example: He11o my name 3s Artem 2029 --> He22o my name 4s Artem 3130

CodePudding user response:

you can use the tr command for this.

echo "$str" | tr '0-9' '1-90' | tr -d '#='

Each character in the first argument is mapped to the corresponding character in the second argument. And it automatically expands ranges of characters, so this is short for tr 012456789 1234567890

CodePudding user response:

Perl to the rescue!

echo 'He11o my name 3s Artem 2029' | perl -pe 's/([0-9])/($1   1) % 10/ge'
  • s/PATTERN/REPLACEMNT/ is substitution;
  • the /g makes "global", it replaces all occurrences;
  • the /e interprets the replacement as code and runs it;
  • the % is the modulo operator, it will make 0 from 10.
  • Related