add tail command

This commit is contained in:
Lisa Milne 2023-12-14 15:45:53 +10:00
parent 8a6e6bb619
commit 0ac73e2a5a

View file

@ -1304,7 +1304,7 @@ head - copy the first part of files
Usage: head [OPTION] <FILE>
Options:
-n the number of lines to print (default 10)
-n N the number of lines to print (default 10)
-? Print this help information
`);
}
@ -1377,6 +1377,120 @@ Options:
return main(args);
});
clite.commands.load('tail',function(args,env,io) {
var stdio = io.include('stdio');
var clite = io.include('clite');
var lines = 10;
var chars = 0;
function help() {
stdio.printf(`
tail - copy the last part of a file
Usage: tail [OPTION] <FILE>
Options:
-n N the number of lines to print (default 10)
-c N instead of lines, print the last N characters
-? Print this help information
`);
}
function writeFile(fd) {
if (!fd) {
stdio.fprintf(io.stderr,'could not open file\n');
io.exit(1);
return;
}
var d = stdio.readAll(fd);
if (chars > 0) {
if (d.length < chars) {
stdio.write(io.stdout,d);
}else{
stdio.write(io.stdout,d.substring(d.length-chars));
}
}else{
var ls = d.split('\n');
if (ls[ls.length-1] == '')
ls.pop();
while (ls.length > lines) {
ls.shift();
}
ls.forEach(function(l) {
stdio.printf('%s\n',l);
});
}
stdio.close(fd);
io.exit(0);
}
function main(args) {
var lnext = false;
var cnext = false;
var short = null;
var file = null;
for (var i=1; i<args.length; i++) {
if (args[i][0] == '-') {
for (var j=1; j<args[i].length; j++) {
switch (args[i][j]) {
case '?':
help();
return 0;
break;
case 'c':
cnext = true;
break;
case 'n':
lnext = true;
break;
default:
stdio.fprintf(io.stderr,'unknown argument: -%c\n',args[i][j]);
}
}
}else if (lnext) {
lines = parseInt(args[i]);
if (lines < 1) {
stdio.fprintf(io.stderr,'invalid lines count "%d"\n',lines);
return 1;
}
lnext = false;
}else if (cnext) {
chars = parseInt(args[i]);
if (chars < 1) {
stdio.fprintf(io.stderr,'invalid characters count "%d"\n',chars);
return 1;
}
cnext = false;
}else if (file == null) {
short = args[i];
file = clite.resolvePath(args[i]);
}else{
stdio.fprintf(io.stderr,'unknown argument: %s\n',args[i]);
}
}
if (file == null) {
stdio.write(io.stderr,'no file specified\n');
return 1;
}
var fd = stdio.open(file,stdio.flags.O_RDONLY,writeFile);
if (!fd) {
stdio.fprintf(io.stderr,'could not open file: %s\n',short);
return 1;
}
return null;
}
return main(args);
});
if (window.location.protocol == 'file:')
clite.commands.load('test',function(args,env,io) {
var stdio = io.include('stdio');