linux使用shell 進行文件數據的讀取與排序


題目

shell腳本語言編寫一個從鍵盤輸入10名學生(含自己)的姓名、 性別、學號和家庭住址,然后按照學號排序,並將排序后的結果在屏幕上按對齊 的方式打印輸出的程序。

代碼

  1. 讀入數據
  2. 數據排序(這里用的選擇排序)
  3. 數據輸出
#!/bin/bash

declare -a username
declare -a sex
declare -a usercode
declare -a userpath

i=0

# scan data from keyboard or pipe
# cat ../test | while read line
for line in `cat ../test`;
do
    index=`expr $i / 4`
    pos=`expr $i % 4`
    if [ $pos -eq 0 ]
    then
        username[$index]=${line}
    elif [ $pos -eq 1 ]
    then
        sex[$index]=${line}
    elif [ $pos -eq 2 ]
    then
        usercode[$index]=${line}
    else
    userpath[$index]=${line}
    fi
    # echo $i, ${usercode[$i]}
    # echo ${username[$i]}, ${sex[$i]}, ${usercode[$i]}, ${userpath[$i]}
    i=$(($i+1))
done

arr=(0 1 2 3 4 5 6 7 8 9)

i=0
j=0

# sort it with ascending
while [ $i -lt 10 ]; do
    j=$(($i+1))
    while [ $j -lt 10 ] ; do
        # echo ${usercode[${arr[$j]}]} ,  ${usercode[${arr[$i]}]}
        if  [ ${usercode[${arr[$j]}]} -lt ${usercode[${arr[$i]}]} ]
        then
            tmp=${arr[$j]}
            arr[$j]=${arr[$i]}
            arr[$i]=$tmp
        fi

        j=$(($j+1))
    done

    i=$(($i+1))
done

# echo ${arr[@]}
i=0
while [ $i -lt 10 ]; do
    index=${arr[$i]}
    printf "%8s %6s %4s %10s\n" ${usercode[$index]}, ${username[$index]}, ${sex[$index]}, ${userpath[$index]}
    i=$(($i+1))
done


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM