0

I have a string which comes from a variable I want to increment it. how can i do that using shell script?

this is my input which comes from a variable:

abc-ananya-01

output should be:

abc-ananya-02
ananya layek
  • 13
  • 1
  • 2

4 Answers4

3

It is shorter:

a=abc-lhg-08
echo ${a%-*}-`printf "%02d" $((10#${a##*-}+1))`
abc-lhg-09

Even better:

a=abc-lhg-08
printf "%s-%02d\n" ${a%-*} $((10#${a##*-}+1))
abc-lhg-09
  • 1
    Nothing in this answer requires `bash` 4, or even any `bash` extensions; it will work in any POSIX shell. – chepner Apr 30 '16 at 18:21
  • In my first example I found a fundamental problem and I corrected it. The original first example can't work with abc-lhg-08 or abc-lhg-09 inputs. I had to suppress the auto octal interpretation of bash when there was a leading zero, with explicit indication of radix ten 10#. I show you what I mean: `a=08;echo $(($a)) bash: 08: value too great for base (error token is "08") a=08;echo $((10#$a)) 8` And there is no reason to use both echo and printf so the second example more fits. – László Szilágyi May 01 '16 at 09:18
1

check this:

kent$  echo "abc-ananya-07"|awk -F'-' -v OFS='-' '{$3=sprintf("%02d",++$3)}7' 
abc-ananya-08

The above codes do the increment and keep your number format.

Kent
  • 189,393
  • 32
  • 233
  • 301
1

With pure Bash it is a bit long:

IFS="-" read -r -a arr <<< "abc-ananya-01"
last=10#${arr[${#arr}-1]}    # to prevent getting 08, when Bash 
                             # understands it is a number in base 8
last=$(( last + 1 ))
arr[${#arr}-1]=$(printf "%02d" $last)
( IFS="-"; echo "${arr[*]}" )

This reads into an array, increments the last element and prints it back.

It returns:

abc-ananya-02
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 1
    `bash` 4.3 now allows negative subscripts, so you can write `last=$((${arr[-1]}+1))` (it's short enough to make a one-liner reasonable). – chepner Apr 30 '16 at 18:18
  • 1
    In fact, you can use `printf -v arr[-1] "%02d" $((arr[-1]+1))` to avoid the need for the temporary `last` variable altogether. – chepner Apr 30 '16 at 18:20
  • This solution doesn't work with these inputs: a='abc-ananya-08' or a='abc-ananya-09' bash error: bash: let: last=08: value too great for base (error token is "08") My correct answer is here: [http://stackoverflow.com/a/36934535/4581311] – László Szilágyi May 01 '16 at 09:48
  • @LászlóSzilágyi yep, hadn't checked that one. Updated, thanks. – fedorqui May 02 '16 at 06:42
1

Bash string manipulations can be used here.

a='abc-ananya-07'
let last=$(echo ${a##*-}+1)
echo ${a%-*}-$(printf "%02d" $last)

enter image description here

sriramganesh
  • 1,460
  • 1
  • 11
  • 7
  • This solution doesn't work with these inputs: a='abc-ananya-08' or a='abc-ananya-09' bash error: bash: let: last=08: value too great for base (error token is "08") My correct answer is here: [http://stackoverflow.com/a/36934535/4581311] – László Szilágyi May 01 '16 at 09:51