Daniel Ferrari
Daniel Ferrari

Reputation: 1

Bash Shell Script - Cut

How i can transform this in a while in bash shell script? Thank you.

a[4]=$(echo $c | cut -c1)
a[3]=$(echo $c | cut -c2)
a[2]=$(echo $c | cut -c3)
a[1]=$(echo $c | cut -c4)
a[0]=$(echo $c | cut -c5)

b[4]=$(echo $d | cut -c1)
b[3]=$(echo $d | cut -c2)
b[2]=$(echo $d | cut -c3)
b[1]=$(echo $d | cut -c4)
b[0]=$(echo $d | cut -c5)

Upvotes: 0

Views: 407

Answers (3)

twalberg
twalberg

Reputation: 62369

If I'm understanding your end goal correctly, here's a quick one-liner (although it uses a couple external utilities, not just bash code):

b=( $( rev <<< "${c}" | sed -e 's/./& /g' ) )

That should take whatever ${c} contains, reverse it, split it into individual characters, and assign each character to an entry in the array b. Note that if the original ${c} contains spaces, those will get lost (i.e. there won't be any array elements containing a space).

Upvotes: 0

dinox0r
dinox0r

Reputation: 16039

There are several ways of getting a reversed string into an array, here is one:

#!/bin/bash

STRING="test string"

# First, reverse the string into a new variable
REV_STRING=$(rev <<< $STRING)

# Declare the array
declare -a ARRAY

ARRAY_LEN=${#REV_STRING}

ARRAY_UPPER_BOUND=$((ARRAY_LEN - 1))

for i in $(seq 0 $ARRAY_UPPER_BOUND); do
    # Here, ${REV_STRING:$i:1} is equivalent to say REV_STRING.charAtPosition(i)
    ARRAY[$i]=${REV_STRING:$i:1}
done

# To print the array content
for i in $(seq 0 $ARRAY_UPPER_BOUND); do
    echo ${ARRAY[$i]}
done

Also, you can use cut in the loop, like this:

#!/bin/bash

STRING="test string"
REV_STRING=$(rev <<< $STRING)

declare -a ARRAY

ARRAY_LEN=${#REV_STRING}

for i in $(seq 1 $ARRAY_LEN); do
    # Here, ${REV_STRING:$i:1} is equivalent to say REV_STRING.charAtPosition(i)
    # ARRAY[$i]=${REV_STRING:$i:1}
    ARRAY[$i]=$(echo $REV_STRING | cut -c$i)
done

# To print the array content
for i in $(seq 1 $ARRAY_LEN); do
    echo ${ARRAY[$i]}
done

Upvotes: 0

anubhava
anubhava

Reputation: 784998

You don't need cut also, following will work:

a=(); for ((i=0; i<5; i++)); do a+=( "${c:$i:1}" ); done
b=(); for ((i=0; i<5; i++)); do b+=( "${d:$i:1}" ); done

Upvotes: 1

Related Questions