今天寫了一個簡單的 Linux Shell 逐行讀取檔案(txt,sh,csv....)的程式,記錄一下,有需要的朋友可以參考。
#!/bin/bash
# Only 1 parameter !
if [ $# != 1 ];then
echo " Usage: .\read.sh filename!";
exit
fi
# check the file !
if ! [ -f $1 ];then
echo "file does not exist!"
exit
elif ! [ -r $1 ];then
echo "file can not be read !"
exit
fi
# PRESS ANY KEY TO CONTITUE !
read -p "begin to read $1 "
# set IFS="\n" , read $1 file per line !
IFS="
"
# i is the line number
i=1
for line in `cat $1`
do
echo line $i:$line
let "i=$i+1"
done
echo "Finished reading file by line ! "
程式雖然簡單,但是細節問題容易出錯,進而浪費寶貴的時間~
PS : 讀取到每一行的資料之後,可以配合使用 cut 指令解析這一行的資料~