To read a file line by line in a Ksh (Korn shell) script on Unix, you can use a while
loop with the read
command. Here’s an example script that demonstrates how to read a file line by line in Ksh:
while read line
do
echo $line
done < file.txt
In this script, the while
loop reads the file file.txt
line by line using the read
command. Each line is stored in the variable line
, and the echo
command is used to print the line to the console.
You can replace the echo
command with any other command that you want to perform on each line of the file. For example, you could use the grep
command to search for a specific pattern in each line:
while read line
do
if [[ $line =~ "pattern" ]]
then
echo $line
fi
done < file.txt
In this example, the if
statement checks whether the line contains the string “pattern”, and if it does, the echo
command is used to print the line to the console.
Note that in Ksh, you can use the [[ ... ]]
syntax for more advanced conditional statements, such as regular expression matches with the =~
operator. If you need to use a single [ ... ]
bracket for compatibility with other shells, you can do so, but some of the more advanced features may not be available.