Sunday, April 29, 2012

Ksh Read a File Line By Line ( UNIX Scripting )

How do I read a file line by line using KSH shell scripting under UNIX like operating systems?

You can use the while loop and read command to read a text file line by line under KSH.

KSH read while loop syntax

#!/bin/ksh
file="/path/to/file.txt"
# while loop
while read line
do
# display line or do somthing on $line
echo "$line"
done <"$file"
In this example, you are reading file separated by | fields. Sample domains.txt:
cyberciti.biz|74.86.48.99
nixcraft.com|75.126.168.152
theos.in|75.126.168.153
cricketnow.in|75.126.168.154
vivekgite.com|75.126.168.155
#!/bin/ksh
# set the Internal Field Separator to a pipe symbol
IFS='|'
 
# file name
file=/tmp/domains.txt
 
# use while loop to read domain and ip
while read domain ip
do
print "$domain has address $ip"
done <"$file"
However, following is recommend syntax to set the Internal field separator (see discussion below):
#!/bin/ksh
# file name
file=/tmp/domains.txt
 
# use while loop to read domain and ip
# set the Internal Field Separator to a pipe symbol
while IFS=\| read domain ip
do
print "$domain has address $ip"
done <"$file"

Suggested readings:

  • ksh man page
Updated for accuracy!

No comments:

Post a Comment