Reputation:
I have a Linux machine (Red Hat Linux 5.1), and I need to add the following task to my Bash script.
Which Linux command or Bash syntax will calculate the next ASCII character?
Remark – the command syntax can be also AWK/Perl, but this syntax must be in my Bash script.
Example:
input results
a --> the next is b
c --> the next is d
A --> the next is B
Upvotes: 7
Views: 1281
Reputation: 435
The character value:
c="a"
To convert the character to its ASCII value:
v=$(printf %d "'$c")
The value you want to add to this ASCII value:
add=1
To change its ASCII value by adding $add to it:
((v+=add))
To convert the result to char:
perl -X -e "printf('The character is %c\n', $v);"
I used -X
to disable all warnings
You can combine all of these in one line and put the result in the vairable $r:
c="a"; add=1; r=$(perl -X -e "printf('%c', $(($add+$(printf %d "'$c"))));")
you can print the result:
echo "$r"
You can make a function to return the result:
achar ()
{
c="$1"; add=$2
printf "$(perl -X -e "printf('%c', $(($add+$(printf %d "'$c"))));")"
}
you can use the function:
x=$(achar "a" 1) // x = the character that follows a by 1
or you can make a loop:
array=( a k m o )
for l in "${array[@]}"
do
echo "$l" is followed by $(achar "$l" 1)
done
Upvotes: 0
Reputation: 15683
You could use chr()
and ord()
functions for Bash (see How do I convert an ASCII character to its decimal (or hexadecimal) value and back?):
# POSIX
# chr() - converts decimal value to its ASCII character representation
# ord() - converts ASCII character to its decimal value
Upvotes: 3
Reputation: 35933
Use translate (tr
):
echo "aA mM yY" | tr "a-yA-Y" "b-zB-Z"
It prints:
bB nN zZ
Upvotes: 8
Reputation: 67908
Perl's ++
operator also handles strings, to an extent:
perl -nle 'print ++$_'
The -l
option with autochomp is necessary here, since a\n
for example will otherwise return 1
.
Upvotes: 4
Reputation: 628
perl -le "print chr(ord(<>) + 1)"
Interactive:
breqwas@buttonbox:~$ perl -le "print chr(ord(<>) + 1)"
M
N
Non-interactive:
breqwas@buttonbox:~$ echo a | perl -le "print chr(ord(<>) + 1)"
b
Upvotes: 0