Signal9Signal9 — home
online
back to labs

Loop Over Files and Total the Lines

MediumShell Scripting10-20 min
The brief

A for loop lets a script act on many files. Combine it with wc -l to tally line counts.

Under /root/logs there are several .txt files. Write a script that loops over them, and writes the GRAND TOTAL number of lines across all of them to /root/out/total.txt (just the number). Then run it.

total=0; for f in /root/logs/*.txt; do n=$(wc -l < "$f"); total=$((total + n)); done; echo "$total" > /root/out/total.txt

Grading recomputes the total across the seeded files and compares. (cat /root/logs/*.txt | wc -l is an equivalent shortcut — either way, the file must hold the right number.)

What you'll do
  • Loop over /root/logs/*.txt summing each file's line count
  • Write the grand total to /root/out/total.txt

Hands-on lab: you work on a real Linux box in your browser, graded on the machine's actual state.