I already know how to put h4 h7 h8 h9 h7
into an array with space as delimiter, but after that I am trying to separate the h
from the numbers to compare the numbers to each other.
How can I do split these in a bash script?
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 community#!/bin/bash
arr=( h4 h7 h8 h9 h7 )
for thing in "${arr[@]}"; do
num=${thing#?}
printf 'The number in "%s" is %d\n' "$thing" "$num"
done
The variable expansion ${variable#pattern}
removes the shortest prefix string matching pattern
from $variable
. The pattern ?
matches a single character.
The output will be
The number in "h4" is 4
The number in "h7" is 7
The number in "h8" is 8
The number in "h9" is 9
The number in "h7" is 7
Alternatively, to ignore remove the non-digit prefix regardless of how long it is, using sed
,
#!/bin/bash
arr=( hello4 happy7 hobbit8 hulk9 hr-department7 )
for thing in "${arr[@]}"; do
num=$( printf '%s\n' "$thing" | sed 's/^[^[:digit:]]*//' )
printf 'The number in "%s" is %d\n' "$thing" "$num"
done
or, using regular expression matching of the digits at the end,
#!/bin/bash
arr=( hello4 happy7 hobbit8 hulk9 hr-department7 )
for thing in "${arr[@]}"; do
if [[ "$thing" =~ ([[:digit:]]+)$ ]]; then
printf 'The number in "%s" is %d\n' "$thing" "${BASH_REMATCH[1]}"
fi
done
printf 'The number in "%s" is %d\n' "$thing" "$num"
?
printf
takes a format string containing format specifiers (here %s
for a string and %d
for a decimal number). The variable data is provided as the extra arguments, and printf
will insert the data in the appropriate places in the format string. It works pretty much the same way as in most programming languages (C and Perl, for example). See also Why is printf better than echo?
echo "The number in $thing is $num"
It'll also produce the same output. Is there any downfall in using like this?
$thing
contains escape sequences like \n
. I know it's very unlikely that your data may use \t
, \n
etc., but other people's data may, and my answer is for anyone who reads it and has a similar problem. Using echo
in their code may do unexpected things depending on what their data actually is. printf
guarantees more consistent output. See Why is printf better than echo?