Read a File Line By Line in UNIX

posted Oct 15, 2014, 11:53 AM by Sachchida Ojha   [ updated Nov 4, 2014, 1:06 PM ]
How do I read a file line by line under UNIX using KSH or BASH shell?
The gadget spec URL could not be found
#!/bin/ksh 
file="/home/vivek/data.txt" 
while read line do # display $line or do somthing with $line 
echo "$line" done <"$file"

#!/bin/bash 
file="/home/vivek/data.txt" 
while IFS= read -r line 
do 
# display $line or do somthing with $line 
echo "$line" done <"$file"
The gadget spec URL could not be found
You can also read field wise:
#!/bin/bash 
file="/etc/passwd" 
while IFS=: read -r f1 f2 f3 f4 f5 f6 f7 do 
# display fields using f1, f2,..,f7 
echo "Username: $f1, Shell: $f7, Home Dir: $f6" done <"$file"
Comments