Monday, April 23, 2012

UNIX: Read a File Line By Line

How do I read a file line by line under UNIX using KSH or BASH shell?

You can use the following syntax using ksh:
#!/bin/ksh
file="/home/vivek/data.txt"
while read line
do
# display $line or do somthing with $line
echo "$line"
done <"$file"
Same code should work with bash too:
#!/bin/bash
file="/home/vivek/data.txt"
while IFS= read -r line
do
# display $line or do somthing with $line
echo "$line"
done <"$file"
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"

No comments:

Post a Comment