본문 바로가기
운영체제 (LNX,WIN)

Bash Script: How read file line by line (best and worst way)

by 날으는물고기 2014. 9. 19.

Bash Script: How read file line by line (best and worst way)

Input: $ cat sample.txt 
This is sample file
This is normal text file

Source: $ cat readfile.sh 
#!/bin/bash

i=1;
FILE=sample.txt

# Wrong way to read the file.
# This may cause problem, check the value of 'i' at the end of the loop
echo "###############################"
cat $FILE | while read line; do
        echo "Line # $i: $line"
        ((i++))
done
echo "Total number of lines in file: $i"

# The worst way to read file.
echo "###############################"
for fileline in $(cat $FILE);do
        echo $fileline 
done

# This is correct way to read file.

echo "################################"
k=1
while read line;do
        echo "Line # $k: $line"
        ((k++))
done < $FILE
echo "Total number of lines in file: $k"

Output: $ ./readfile.sh 
###############################
Line # 1: This is sample file
Line # 2: This is normal text file
Total number of lines in file: 1
###############################
This
is
sample
file
This
is
normal
text
file
################################
Line # 1: This is sample file
Line # 2: This is normal text file
Total number of lines in file: 3  




출처 : linuxpoison.blogspot.kr

728x90

댓글