Reading Files Line By Line
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 20 of 39.
A while read loop reads a file one line at a time. read -r line puts the next line in line, and the loop ends when the file has no lines left. done < file sends the file into the loop. IFS= keeps the spaces at the start and end of each line, and -r keeps backslashes as they are.
n=1
while IFS= read -r line; do
echo "$n: $line"
((n++))
done < todo.txtFor a CSV, write IFS=, and give read one variable per column: it splits each line at the commas. To skip a header, read it once before the loop. The braces group both commands so they read from the same file:
{
read -r header
while IFS=, read -r city temp; do
echo "$city is at $temp degrees"
done
} < temps.csvWhen temps.csv holds city,temp, Oslo,4 and Cairo,31, this prints Oslo is at 4 degrees and Cairo is at 31 degrees. The last variable takes the rest of the line, commas included.
Challenge
MediumWrite a script that reads a stock CSV and flags items that are running low.
- Open
stock.sh. Its first argument is a CSV file whose first line is the headeritem,qty. - Skip the header, then read each row into
itemandqty. - For each row print
ITEM: QTY, and add(low)at the end of the line when QTY is under 5. - Save the file.
Try it: run bash stock.sh stock.csv. It prints:
apples: 12
pears: 3 (low)
plums: 40
figs: 0 (low)Then run bash stock.sh deli.csv, where one item name has a space:
blue cheese: 2 (low)
ham: 7Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV ReportPractice on your own: Terminal playground