File Statistics in Shell

Level 3120 keystrokes

Loops over the .txt files in the current directory, prints each name and counts them. The output depends on the files present (here data.txt and notes.txt).

Shell code

# Start the counter at 0
1count=0
# The glob *.txt expands to the .txt files in the current directory
2for f in *.txt; do
# If nothing matches, f is the literal "*.txt"; -f skips that case
3 if [ -f "$f" ]; then
# Add 1 with arithmetic expansion
4 count=$((count + 1))
# Print the file name
5 echo "Found: $f"
6 fi
7done
# Print how many .txt files were found
8echo "Total: $count files"

Output

Found: data.txt
Found: notes.txt
Total: 2 files
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 6
  • $× 4
  • ;× 2
  • :× 2
  • (× 2
  • )× 2
  • =× 2
  • -× 1
  • .× 1
  • [× 1

More Shell examples at level 3

← Shell typing practice