Read File Lines in Shell

Level 393 keystrokes

A while read loop reads data.txt one line at a time and prints each line with its line number. IFS= and -r keep each line exactly as written.

Shell code

# Line counter
1count=0
# IFS= keeps leading/trailing spaces; -r keeps backslashes as is
# read returns false at end of file, which ends the loop
2while IFS= read -r line; do
# Count this line
3 count=$((count + 1))
# Print the line number and the line
4 echo "$count: $line"
# < data.txt feeds the file to the whole loop as standard input
5done < data.txt

Output

1: First line
2: Second line
3: Third line
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.

  • =× 3
  • $× 3
  • "× 2
  • (× 2
  • )× 2
  • -× 1
  • ;× 1
  • :× 1
  • .× 1
  • +× 1

More Shell examples at level 3

← Shell typing practice