Wuju Style
Wuju Style

Reputation: 11

how to increment all digits in string(Bash Script)

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

Upvotes: 1

Views: 174

Answers (2)

Barmar
Barmar

Reputation: 781058

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

Upvotes: 4

choroba
choroba

Reputation: 241898

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.

Upvotes: 1

Related Questions