1

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?

4
#!/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
6
  • +1 Nice, Can you please explain this part: printf 'The number in "%s" is %d\n' "$thing" "$num" ?
    – User123
    Dec 19 '18 at 10:02
  • 2
    @User123 It's a standard way of outputting a string containing variable data. 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?
    – Kusalananda
    Dec 19 '18 at 10:04
  • Thanks!! But if i use: echo "The number in $thing is $num" It'll also produce the same output. Is there any downfall in using like this?
    – User123
    Dec 19 '18 at 10:08
  • 2
    @User123 Not if $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?
    – Kusalananda
    Dec 19 '18 at 10:11
  • @User123 Sorry, I confused you with the person asking the question. Nevertheless...
    – Kusalananda
    Dec 19 '18 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.