davoid davoid - 10 days ago 6
Bash Question

Concatenating digits from a string in sh

Assuming that I have a string like this one:

string="1 0 . @ 1 1 ? 2 2 4"


Is it possible to concatenate digits that are next to each other?

So that
string
be like:
10 . @ 11 ? 224
?

I found only basic things how to distinguish integers from other characters and how to "connect" them. But I have no idea how to iterate properly.

num=""
for char in $string; do
if [ $char -eq $char 2>/dev/null ] ; then
num=$num$char

Answer

Here's an almost pure-shell implementation -- transforming the string into a character per line and using a BashFAQ #1 while read loop.

string="1 0 . @ 1 1 ? 2 2 4"
output=''

# replace spaces with newlines for easier handling
string=$(printf '%s\n' "$string" | tr ' ' '\n')

last_was_number=0
printf '%s\n' "$string" | {
  while read -r char; do
    if [ "$char" -eq "$char" ] 2>/dev/null; then # it's a number
      if [ "$last_was_number" -eq "1" ]; then
        output="$output$char"
        last_was_number=1
        continue
      fi
      last_was_number=1
    else
      last_was_number=0
    fi
    output="$output $char"
  done
  printf '%s\n' "$output"
}
Comments