Skip to content

Commit 64e23bd

Browse files
committed
Implement cat command with -n and -b support
1 parent 3f26722 commit 64e23bd

1 file changed

Lines changed: 50 additions & 0 deletions

File tree

  • implement-shell-tools/cat

implement-shell-tools/cat/cat.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
const fs = require("fs");
2+
3+
const args = process.argv.slice(2);
4+
5+
let flag = "";
6+
let lineNumber = 1;
7+
8+
for (const arg of args) {
9+
10+
// Check for flags
11+
if (arg === "-n" || arg === "-b") {
12+
flag = arg;
13+
continue;
14+
}
15+
16+
// Read the file
17+
const content = fs.readFileSync(arg, "utf8");
18+
19+
// split into lines
20+
const lines = content.split("\n");
21+
22+
// Remove the extra empty line if the file ends with a new line
23+
if (lines[lines.length - 1] === "") {
24+
lines.pop();
25+
}
26+
27+
28+
for (const line of lines) {
29+
30+
if (flag === "-n") {
31+
console.log(`${lineNumber}\t${line}`);
32+
lineNumber++;
33+
}
34+
35+
else if (flag === "-b") {
36+
37+
if (line === "") {
38+
console.log("");
39+
} else {
40+
console.log(`${String(lineNumber).padStart(6)} ${line}`);
41+
lineNumber++;
42+
}
43+
44+
}
45+
46+
else {
47+
console.log(line);
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)