Skip to content

Instantly share code, notes, and snippets.

@cubapp
Created January 16, 2018 07:50
Show Gist options
  • Save cubapp/12803a19a4214a588b0bafcb77f24ba8 to your computer and use it in GitHub Desktop.
Save cubapp/12803a19a4214a588b0bafcb77f24ba8 to your computer and use it in GitHub Desktop.
Last 5 - get the last 5 characters from each line of a text file. From http://www.thelinuxrain.com/articles/bash-drivers-start-your-engines
#include <stdio.h>
#include <stdlib.h>
// from http://www.thelinuxrain.com/articles/bash-drivers-start-your-engines
// C version is about 2-4 times faster than perl version.
int main (int argc, char *argv[])
{
if (argc != 2){
printf("Usage: %s filename\n", argv[0]);
exit(1);
}
FILE *fp;
if ((fp = fopen(argv[1],"r"))==NULL){
printf("Can not open file %s \n",argv[1]);
exit(1);
}
char *line = NULL;
size_t len = 0;
ssize_t read;
while ((read = getline(&line, &len, fp)) != -1 ) {
if (len>5){
printf("%s", line + read - 6);
}
}
free (line);
fclose(fp);
}
@cubapp
Copy link
Author

cubapp commented Jan 16, 2018

C version: 1.28s
awk version: 25.29s
perl version: 4.79s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment