shell split文字列の例

1212 ワード

http://stackoverflow.com/questions/1617771/splitting-string-into-array
 
$ cat split.sh
#!/bin/sh

# Script to split fields into tokens

# Here is the string where tokens separated by colons
s="first column:second column:third column"
ip_arr=()
IFS=":"     # Set the field separator
set $s      # Breaks the string into $1, $2, ...
i=0
for item    # A for loop by default loop through $1, $2, ...
do
    ip_arr=("${ip_arr[@]}" "$item")
    echo "Element $i: $item"
    ((i++))
done