Skip to content

Commit e785ce0

Browse files
committed
implement wc
1 parent 85bb502 commit e785ce0

File tree

1 file changed

+65
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+65
-0
lines changed

implement-shell-tools/wc/wc.mjs

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
program
5+
.name("wc")
6+
.description("Display numbers of line, words, and bytes in each file")
7+
.option("-l", "Number of lines")
8+
.option("-w", "Number of words")
9+
.option("-c", "Number of bytes")
10+
.argument("<path...>");
11+
12+
program.parse();
13+
14+
const options = program.opts();
15+
const paths = program.args;
16+
17+
let totalLines = 0;
18+
let totalWords = 0;
19+
let totalBytes = 0;
20+
21+
for(const path of paths){
22+
let content;
23+
try{
24+
content = await fs.readFile(path, "utf-8");
25+
} catch (err){
26+
console.error(`Error reading file "${path}":`, err.message);
27+
continue;
28+
}
29+
30+
const lines = content.replace(/\n$/, "").split("\n");
31+
32+
const words = content.trim().split(/\s+/); // handles multiple spaces
33+
const { size } = await fs.stat(path);
34+
35+
const lineCount = lines.length;
36+
const wordCount = words.length;
37+
const byteCount = size;
38+
39+
totalLines += lineCount;
40+
totalWords += wordCount;
41+
totalBytes += byteCount;
42+
43+
if(options.l) {
44+
console.log(`\t${lineCount} ${path}`);
45+
} else if(options.w) {
46+
console.log(`\t${wordCount} ${path}`);
47+
} else if(options.c) {
48+
console.log(`\t${byteCount} ${path}`)
49+
} else {
50+
console.log(`\t${lineCount}\t${wordCount}\t${size} ${path}`);
51+
}
52+
53+
}
54+
55+
if (paths.length > 1) {
56+
if (options.l) {
57+
console.log(`\t${totalLines} total`);
58+
} else if (options.w) {
59+
console.log(`\t${totalWords} total`);
60+
} else if (options.c) {
61+
console.log(`\t${totalBytes} total`);
62+
} else {
63+
console.log(`\t${totalLines}\t${totalWords}\t${totalBytes} total`);
64+
}
65+
}

0 commit comments

Comments
 (0)