I don't know the bash tools well enough to give a cool one-line answer, so here is a python script instead.
Usage
- Save the code in a file
increment.py
;
- Make the file executable with
chmod +x increment.py
;
- Run the script with
./increment.py blablabla 123
.
Code
#!/usr/bin/env python3
import sys
def print_help(argv0):
print('increment numbers by 1')
print('example usage:')
print(' {} B-Funny Flash Nonfiction 202105131635'.format(argv0))
print(' B-Funny Flash Nonfiction 202105131636')
def main(argv):
if len(argv) < 2:
print_help(argv[0])
else:
for s in argv[1:]:
if s.isnumeric():
print(int(s) + 1, end=' ')
else:
print(s, end=' ')
print()
if __name__=='__main__':
main(sys.argv)
Explanation
In a python program called from the command-line, the command-line arguments are stored in the array sys.argv
.
The first element of the array, with index 0
, is the name that was used to call the program, most likely "./increment.py"
in our case.
The remaining elements are the parameters that were passed to the program; the words "B-Funny"
, "Flash"
, "Nonfiction"
, "202105131635"
in our case.
The for-loop for s in argv[1:]:
iterates on the elements of argv
, but starting with the element 1 (thus ignoring the element 0). Each of these elements is a string; the method .isnumeric
is used to check whether this string represents a number or not. Refer to the documentation on .isnumeric
.
If the string is not numeric, we print is as-is. If the string is numeric, we compute the number it represents by calling int(s)
, then we add 1, and we print the result.
Apart from that, the line if len(argv):
checks whether argv
contains at least two elements; if it doesn't, that means it only contains its element 0, which is "./increment.py"
; in this case, instead of printing the arguments, the script calls the function print_help
which explains how to use the program.
Finally, the bit about if __name__ == '__main__':
is a python idiom to check whether the file increment.py
was run as a program or as a module imported by another file. Refer to this question.