Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions implement-shell-tools/cat/cat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const fs = require("fs");

const args = process.argv.slice(2);

let flag = "";
let lineNumber = 1;

for (const arg of args) {

// Check for flags
if (arg === "-n" || arg === "-b") {
flag = arg;
continue;
}

// Read the file
const content = fs.readFileSync(arg, "utf8");

// split into lines
const lines = content.split("\n");

// Remove the extra empty line if the file ends with a new line
if (lines[lines.length - 1] === "") {
lines.pop();
}


for (const line of lines) {

if (flag === "-n") {
console.log(`${lineNumber}\t${line}`);
lineNumber++;
}

else if (flag === "-b") {

if (line === "") {
console.log("");
} else {
console.log(`${String(lineNumber).padStart(6)} ${line}`);
lineNumber++;
}

}

else {
console.log(line);
}
}
}
41 changes: 41 additions & 0 deletions implement-shell-tools/ls/ls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const fs = require("fs");
const path = require("path");
const args = process.argv.slice(2);

let onePerLine = false;
let showAll = false;
let target = ".";

for (const arg of args) {

if (arg === "-1") {
onePerLine = true;
}
else if (arg === "-a") {
showAll = true;
}
else {
target = arg;
}
}

const stats = fs.statSync(target);
if (stats.isFile()) {
console.log(path.basename(target));
} else {

let files = fs.readdirSync(target);

if (!showAll) {
files = files.filter(file => !file.startsWith("."));
}
if (onePerLine) {

for (const file of files) {
console.log(file);
}

} else {
console.log(files.join(" "));
}
}
46 changes: 46 additions & 0 deletions implement-shell-tools/wc/wc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const fs = require("fs");

const args = process.argv.slice(2);

let showWords = false;
let showChars = false;
let showLines = false;
let fileNames = [];

// Check flags and file names
for (let item of args) {
if (item === "-l") {
showLines = true;
} else if (item === "-w") {
showWords = true;
} else if (item === "-c") {
showChars = true;
} else {
fileNames.push(item);
}
}

// If no flags are given, show everything
if (!showLines && !showWords && !showChars) {
showLines = true;
showWords = true;
showChars = true;
}

for (let fileName of fileNames) {
let text = fs.readFileSync(fileName, "utf8");

let totalLines = text.split("\n").length - 1;
let totalWords = text.trim().split(/\s+/).length;
let totalChars = Buffer.byteLength(text);

let output = "";

if (showLines) output += totalLines + " ";
if (showWords) output += totalWords + " ";
if (showChars) output += totalChars + " ";

output += fileName;

console.log(output);
}
Loading