Tuesday, 14 January 2020

How to Process a File Line by Line


Sometimes you need to process a file line by line. You can do this as follows:
 
First you need a file. Here is one I made earlier:
 
Linux > cat input_file
0123456789
9876543210
ABCDEFGHIJ
KLMNOPQRST
Linux >
 
I wrote this script to process the file I had created:
 
Linux > cat script.ksh
#!/bin/bash
i=1
for j in `cat input_file`
do
echo "Line $i = $j"
((i+=1))
done
Linux >
 
It produced the following output when I ran it:
 
Linux > ./script.ksh
Line 1 = 0123456789
Line 2 = 9876543210
Line 3 = ABCDEFGHIJ
Line 4 = KLMNOPQRST
Linux >