Which of the following UNIX/Linux pipes will count the number of lines in all…
2019
Which of the following UNIX/Linux pipes will count the number of lines in all the files having .c and .h as their extension in the current working directory?
- A.
cat ∗⋅ ch ∣ wc −1
- B.
cat ∗⋅[ c-h ]∣ wc −1
- C.
cat ∗⋅[ ch ]∣ ls −1
- D.
cat ∗⋅[ ch ]∣ wc - 1
Attempted by 36 students.
Show answer & explanation
Correct answer: D
Correct command: cat *.[ch] | wc -l
Why this works:
The glob pattern *.[ch] matches files whose names end with .c or .h.
cat concatenates the contents of those files and writes them to standard output.
wc -l reads the input and counts the number of newline characters, giving the total number of lines.
Common mistakes to avoid:
Using [c-h] creates a character range (c through h) rather than matching the two extensions .c and .h. Use [ch] to list the two characters explicitly.
Confusing the digit '1' with the letter 'l' in the wc flag. The correct flag to count lines is -l (lowercase L).
Piping to ls -1 lists filenames instead of counting lines — use wc -l to count lines.
Alternative:
wc -l *.[ch] will print the line count for each matching file and a total. If you only want the combined total as a single number, use cat *.[ch] | wc -l.
A video solution is available for this question — log in and enroll to watch it.