Sam
Sam

Reputation: 157

How can I replace a number with one higher

I have a bash script for macOS, which replaces the last character (a number) on the first line of a document with the number plus one. For example, if the number was 19, it would be replaced with 20 (I know that the code only replaces the last character). Here's the code that I currently have:

#For some reason the -e (not -E) is necessary here
RC01=$(sed -ne "1s/.*\(.\)$/\1/p" ./document)
RC02=${RC01}
let "RC02++"
sed -i '' -n "1s/${RC01}/${RC02}/" ./document

When the last line runs, if the document has a first line with anything on it, it clears the whole document.

What's going wrong, and how can I fix it?

Upvotes: 0

Views: 262

Answers (1)

tripleee
tripleee

Reputation: 189908

Your immediate problem is that sed -n suppresses all printing of output lines.

You can fix this easily by removing the -n;

RC01=$(sed -n "1s/.*\(.\)$/\1/p" ./document)
RC02=${RC01}
let "RC02++"
sed -i '' "1s/${RC01}\$/${RC02}/" ./document

This still has the problem that you only increment the very last digit; if your number has more than one digit, this will lead to weirdness like 18, 19, 110, 111 rather than 18, 19, 20, 21

RC01=$(sed -n "s/\(.*[^0-9]\)\([0-9]*\)$/\2/p;q" ./document)
RC02=${RC01}
let "RC02++"
sed -i '' "1s/${RC01}\$/${RC02}/" ./document

The -i feature of sed is hard to beat for replacing a file in place. If it weren't for that, I would definitely recommend Awk instead. Here's a quick attempt.

awk 'NR == 1 { $NF = 1+$NF }1' ./document >./document.tmp &&
mv ./document.tmp ./document

Perl has the best of both worlds, with sugar on top;

perl -pi -e 's/(\d+)$/1+$1/e if $. == 1' ./document

Upvotes: 2

Related Questions