Tuesday, August 30, 2016

Linux Shell Script Bash Read line by line in While Loop and Print Even lines


What the code does:

It reads from the given file line by line using while loop. Next it check if the line number is even or, odd using if condition and prints the even lines.

Sample Input File:

save it as FaxNumbers.txt
+(country code)-(area code)-(fax number)
+1-212-9876543
+44-208-1234567
+443-208434-12345674
+233-11-114567
+190-209-1234567
+1-212-9876543
+44-208-1234567
+443-208434-12345674
+233-11-114567
view raw FaxNumbers.txt hosted with ❤ by GitHub

Code to Print Even Lines:

Save it as "EvenLinePrinter.sh".
#!/bin/bash
i=1
while read line
do
var=$(( $i % 2 ))
if [ $var -eq 0 ]; then
echo "$line"
fi
i=$(( $i + 1 ))
done < "FaxNumbers.txt"

Run The Code:

bash EvenLinePrinter.sh

No comments: