shell file read line

OS/리눅스 & 유닉스 2012. 3. 20. 13:12

How to read file line by line? (sh)

In general, use "while" to loop call "read" :

All example is in #!/bin/sh 

1.

readline1 ()
{
inputFile=$1
cat $inputFile | while read LINE
do
        echo $LINE

done
}

 

2.

readline2 () 
{

       inputFile=$1
       while read LINE
       do
               echo $LINE
       done < $1
}

3.

readline3 () 
{

        inputFile=$1
        while line LINE
        do
                echo $LINE
        done < $1
}

 

note: realine3 will echo 2 nowline, becase "line" will read the content include newline.


4.

readline4 ()
{
exec    3<&0
exec  0<$1
while read LINE
do
    print $LINE
done

exec 0<&3
}
using fd redirection.

====================================================================

Using for loop -

for i in `cat TestFile`
do
echo $i
done

or

Using While loop -

while read line
do
echo $line
done < TestFile 

=====================================================================
 # User define Function (UDF)

processLine(){
  line="$@" # get all args
  #  just echo them, but you may need to customize it according to your need
  # for example, F1 will store first field of $line, see readline2 script
  # for more examples
  # F1=$(echo $line | awk '{ print $1 }')
  echo $line
}
 
### Main script stars here ###
# Store file name
FILE=""
 
# Make sure we get file name as command line argument
# Else read it from standard input device
if [ "$1" == "" ]; then
   FILE="/dev/stdin"
else
   FILE="$1"
   # make sure file exist and readable
   if [ ! -f $FILE ]; then
  	echo "$FILE : does not exists"
  	exit 1
   elif [ ! -r $FILE ]; then
  	echo "$FILE: can not read"
  	exit 2
   fi
fi
# read $FILE using the file descriptors
 
# Set loop separator to end of line
BAKIFS=$IFS
IFS=$(echo -en "\n\b")
exec 3<&0
exec 0<$FILE
while read line
do
	# use $line variable to process line in processLine() function
	processLine $line
done
exec 0<&3
 
# restore $IFS which was used to determine what the field separators are
IFS=$BAKIFS
exit 0

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

awk  (0) 2012.03.20
Four Ways to Pass Shell Variables in AWK  (0) 2012.03.20
awk 외부 변수 참조  (0) 2012.03.20
쉘 (shell) 프로그래밍  (0) 2012.03.20
apache config  (0) 2012.03.20
: