How do I get the first digit from a number? For example, 25 - to get only the "2" from the 25.
This is what I tried:
echo -n "Enter age: "
read age
echo $(s:0:1)
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityHow do I get the first digit from a number? For example, 25 - to get only the "2" from the 25.
This is what I tried:
echo -n "Enter age: "
read age
echo $(s:0:1)
You're using the wrong variable s
instead of age
and parameter expansion works with curly braces ${...}
:
read -p "Enter age: " age
echo "${age:0:1}"
The most basic and POSIX compatible way (assuming no sign) is:
echo "${age%"${age#?}"}"
In some shells (bash,ksh,zsh):
echo "${age:0:1}"
If the value could contain a sign, remove it first:
$ age=+23
$ age=${age#[+-]}
$ echo "${age%"${age#?}"}"
2
printf '%s\n' "${age[1]}"
in zsh or yash (or printf '%s\n' $age[1]
in zsh). Beware echo -
outputs an empty line in zsh (as -
is the end of option delimiter)
Apr 28, 2020 at 11:29
-
by using echo --
instead; many commands accept --
as a delimiter to mean "what follows are positional arguments, not options"... but it will depend on what echo
is being used. (Note that echo
is often a shell built-in.)
--
as meaning "end of options", none. All will just output a --
. Try it.
${age[1]}
and $age[1]
are zshisms, only work inside zsh and are not portable. Why use a "limited to one particular shell" syntax when a more portable solution also exist ?. (2) There is no issue with echo -
as the -
either doesn't exist (no sign) or, if it exists, it is removed with age=${age#[+-]}
. Read the answer.
${a[1]}
is zsh or yash like I said. Those are additional notes to complement your answer (which already mentions ksh93isms), it's not a critic to your answer. echo ${a:0:1}
will output an empty line if $a
is -1
, it's still worth noting.
Apr 28, 2020 at 18:23
As you mention bash
in the title:
#!/bin/bash
read -p 'Enter a number: '
printf '%.1s\n' "$REPLY"
This prints only the first character of the string $REPLY
(read by read
).
To store this in another variable, othervar
, use
printf -v othervar '%.1s' "$REPLY"
You could also just use a simple variable substitution, as mentioned by others,
printf '%s\n' "${REPLY:0:1}"
where 0
is the zero-based position in the string where we want to start pulling out data, and 1
is the length of the substring that we want.
You can assign ${REPLY:0:1}
to another variable directly:
othervar=${REPLY:0:1}
POSIX compatible solution:
#!/usr/bin/env sh
printf "Enter age: "
read -r age
echo "$age"
echo first digit: "$(echo "$age" | cut -c1)"
Example:
$ ./script.sh
Enter age: 25
25
first digit: 2
"${age:0:1}"
.
s
supposed to be in the third line?${s:0:1}
, not a command substitution$(s:0:1)
(which should give you a command-not-found error, not the literal strings:0:1
).