Ksh逐行读取文件(UNIX脚本)

时间:2020-01-09 10:41:09  来源:igfitidea点击:

如何在UNIX之类的操作系统下使用KSH Shell脚本逐行读取文件?
您可以使用while循环和读取命令在KSH下逐行读取文本文件。

KSH read while循环语法

#!/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"

在此示例中,您正在读取用|分隔的文件。领域。 domains.txt示例:

theitroad.local|10.16.48.99
theitroad.com|75.126.168.152
theitroad.com|75.126.168.153
cricketnow.in|75.126.168.154
Hymangite.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"

但是,建议使用以下语法来设置内部字段分隔符

#!/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"