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|188.8.131.52 nixcraft.com|184.108.40.206 theos.in|220.127.116.11 cricketnow.in|18.104.22.168 vivekgite.com|22.214.171.124
#!/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"
- ksh man page
Updated for accuracy!TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!
- 30 Cool Open Source Software I Discovered in 2013
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop