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 IFS= read -r 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:

sxi.io|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!

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.