Neon Flash
Neon Flash

Reputation: 3233

bash awk split string into array

I am using awk to split a string into array using a specific delimiter. Now, I want to perform some operation on each element of the array.

I am able to extract a single element like this:

#! /bin/bash

b=12:34:56
a=`echo $b | awk '{split($0,numbers,":"); print numbers[1]}'`
echo $a

I want to do something like this:

#! /bin/bash

b=12:34:56
`echo $b | awk '{split($0,numbers,":");}'`
for(i=0;i<length(numbers);i++)
{
   // perform some operation using numbers[i]
}

how would I do something like this in bash scripting?

Upvotes: 6

Views: 40282

Answers (5)

user153275
user153275

Reputation:

None of these answers used awk (weird). With awk you can do something like:

echo 12:34:56 | awk '{split($0,numbers,":")} END {for(n in numbers){ print numbers[n] }}'

replacing print numbers[n] with whatever it is you want to do.

Upvotes: 20

vkersten
vkersten

Reputation: 161

Another neat way, not using awk, but build-in 'declare':

b=12:34:56

# USE IFS for splitting (and elements can have spaces in them)
IFS=":"
declare -a elements=( $b )
#show contents
for (( i=0 ; i < ${#elements[@]}; i++ )); do
    echo "$i= ${elements[$i]}"
done

Upvotes: 1

chepner
chepner

Reputation: 531165

The bash read command can split a string into an array by itself:

IFS=: read -a numbers <<< "$b"

To see that it worked:

echo "Hours: ${numbers[0]}"
echo "Minutes: ${numbers[1]}"
echo "Seconds: ${numbers[2]}"

for val in "${numbers[@]}"; do
   seconds=$(( seconds * 60 + $val ))
done

Upvotes: 2

ensc
ensc

Reputation: 6984

b=12:34:56
IFS=:
set -- $b
for i; do echo $i; done

This does not contain bashisms but works with every sh.

Upvotes: 6

Mat
Mat

Reputation: 206689

You don't really need awk for that, bash can do some string processing all by itself.

Try:

b=12:34:56
for element in ${b//:/ } ; do
  echo $element
done

If you need a counter, it's pretty trivial to add that.

See How do I do string manipulations in bash? for more info on what you can do directly in bash.

Upvotes: 17

Related Questions