Skip to content

Commit 6dd0b3a

Browse files
committed
implement cat command with -n and -b flag support
1 parent 3de450e commit 6dd0b3a

1 file changed

Lines changed: 36 additions & 19 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.js

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,42 @@ import { promises as fs } from "node:fs";
33
import process from "node:process";
44

55
program
6-
.name("count-containing-words")
7-
.description("Counts words in a file that contain a particular character")
8-
.option("-c, --char <char>", "The character to search for", "e")
9-
.argument("<path>", "The file path to process");
6+
.name("display-file-content")
7+
.description("Implement cat command with -n and -b flag support")
8+
.option("-n, --number-all-lines", "Number every line in the file")
9+
.option("-b, --number-non-empty-lines", "Number non empty lines in the file")
10+
.argument("<paths...>", "File paths to process");
1011

11-
program.parse();
12+
program.parse(process.argv);
1213

13-
const argv = program.args;
14-
if (argv.length != 1) {
15-
console.error(
16-
`Expected exactly 1 argument (a path) to be passed but got ${argv.length}.`
17-
);
18-
process.exit(1);
19-
}
20-
const path = argv[0];
21-
const char = program.opts().char;
14+
const args = program.args; //Array all file paths
2215

23-
const content = await fs.readFile(path, "utf-8");
24-
const countOfWordsContainingChar = content
25-
.split(" ")
26-
.filter((word) => word.includes(char)).length;
27-
console.log(countOfWordsContainingChar);
16+
//read flags user typed and return them as object.
17+
const opts = program.opts();
18+
19+
let lineNumber = 1;
20+
21+
// Loop over every filepath in args
22+
args.forEach(async (filepath) => {
23+
const content = await fs.readFile(filepath, "utf8");
24+
const lines = content.split("\n");
25+
26+
lines.forEach((line) => {
27+
if (opts.numberAllLines) {
28+
// -n: number every line
29+
console.log(`${lineNumber} ${line}`);
30+
lineNumber++;
31+
} else if (opts.numberNonEmptyLines) {
32+
// -b: number non-empty lines only
33+
if (line.trim() === "") {
34+
console.log(line);
35+
} else {
36+
console.log(`${lineNumber} ${line}`);
37+
lineNumber++;
38+
}
39+
} else {
40+
// No flag: just print
41+
console.log(line);
42+
}
43+
});
44+
});

0 commit comments

Comments
 (0)