Comment

Comment by kazinator

C version. Maybe this logic should be built into GNU find as an option!

  $ find /etc/network | ./frangi-cheat 
  /etc/network
              /if-post-down.d
                             /wireless-tools
                             /wpasupplicant
                             /avahi-daemon
              /if-down.d
                        /resolvconf
                        /wpasupplicant
                        /avahi-autoipd
              /interfaces.d
              /interfaces
              /if-pre-up.d
                          /wireless-tools
                          /wpasupplicant
                          /ethtool
              /if-up.d
                      /ntpdate
                      /wpasupplicant
                      /000resolvconf
                      /openssh-server
                      /ethtool
                      /avahi-autoipd
                      /slrn
                      /avahi-daemon

  $ cat frangi-cheat.c
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  int main(void)
  {
    char old_line[FILENAME_MAX] = "", line[FILENAME_MAX];

    while (fgets(line, sizeof line, stdin)) {
      char *p = line, *o = old_line, *nl = strchr(line, '\n');

      if (nl)
        *nl = 0;

      while (*p && *o) {
        char *op = p;

        if (*o == '/' && *p == '/')
          o++, p++;

        size_t lp = strcspn(p, "/");
        size_t lo = strcspn(o, "/");

        if (lp == lo && !strncmp(p, o, lp)) {
          p += lp;
          o += lp;
          printf("%*s", (int) (p - op), "");
          continue;
        }

        p = op;
        break;
      }

      puts(p);
      strcpy(old_line, line);
    }

    return feof(stdin) ? EXIT_SUCCESS : EXIT_FAILURE;
  }
Note: yes, we could swap pointers between two buffers instead of strcpy.
parent kazinator 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton