basename.c 1019 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* basename.c - Return non-directory portion of a pathname
  2. *
  3. * Copyright 2012 Tryn Mirell <tryn@mirell.org>
  4. *
  5. * See http://opengroup.org/onlinepubs/9699919799/utilities/basename.html
  6. USE_BASENAME(NEWTOY(basename, "^<1as:", TOYFLAG_USR|TOYFLAG_BIN))
  7. config BASENAME
  8. bool "basename"
  9. default y
  10. help
  11. usage: basename [-a] [-s SUFFIX] NAME... | NAME [SUFFIX]
  12. Return non-directory portion of a pathname removing suffix.
  13. -a All arguments are names
  14. -s SUFFIX Remove suffix (implies -a)
  15. */
  16. #define FOR_basename
  17. #include "toys.h"
  18. GLOBALS(
  19. char *s;
  20. )
  21. void basename_main(void)
  22. {
  23. char **arg;
  24. if (toys.optflags&FLAG_s) toys.optflags |= FLAG_a;
  25. if (!(toys.optflags&FLAG_a)) {
  26. if (toys.optc > 2) error_exit("too many args");
  27. TT.s = toys.optargs[1];
  28. toys.optargs[1] = NULL;
  29. }
  30. for (arg = toys.optargs; *arg; ++arg) {
  31. char *base = basename(*arg), *p;
  32. // Chop off the suffix if provided.
  33. if (TT.s && *TT.s && (p = strend(base, TT.s))) *p = 0;
  34. puts(base);
  35. }
  36. }