您的位置:首页 > 运维架构 > Shell

shell按行从文件读取, 分割成数组

2015-06-08 13:53 746 查看
cut -d 如果找不到分割符号, 就会输出原字符串,无聊-f后面是什么,加-s就什么都不输出了

#!/bin/bash

# 从文件中按行读取,每行分割成字符串, 形成数组# 
j=0
while read line
do
    i=1
    while :
    do
        str=` echo $line | cut -d ":" -f $i `
        #echo $i, $str
        if [ "$str" == "$line" ];then
            arr[j]=$str
            break
        elif [ "$str" != "" ];then
            arr[j]=$str
        else
            break
        fi
        i=$(($i+1))
        j=$(($j+1))
    done
done < a.txt

# 数组遍历方式 #
for a in ${arr[@]};do
     echo $a
done
echo "---------- c for each --"
for((i=0;i<${#arr[@]};i++));do
     echo $i, ${arr[$i]}
done
# 2 #
echo "======== w2"
while read line
do
    arr2=` echo "$line" | tr ':' ' ' | tr -s ' ' `
done < a.txt

for((i=0;i<${#arr2[@]};i++));
do
   echo $i, ${arr2[$i]}
done
echo "========seq"
for item in ${arr2[@]};do
     echo $item
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: