5 * Returns the length of a line, without trailing spaces.
7 * If the line ends with newline, it will be removed too.
9 static size_t cleanup(char *line, size_t len)
12 if (line[len - 1] == '\n')
16 unsigned char c = line[len - 1];
26 * Remove empty lines from the beginning and end
27 * and also trailing spaces from every line.
29 * Note that the buffer will not be NUL-terminated.
31 * Turn multiple consecutive empty lines between paragraphs
32 * into just one empty line.
34 * If the input has only empty lines and spaces,
35 * no output will be produced.
37 * If last line has a newline at the end, it will be removed.
39 * Enable skip_comments to skip every line starting with "#".
41 size_t stripspace(char *buffer, size_t length, int skip_comments)
44 size_t i, j, len, newlen;
47 for (i = j = 0; i < length; i += len, j += newlen) {
48 eol = memchr(buffer + i, '\n', length - i);
49 len = eol ? eol - (buffer + i) + 1 : length - i;
51 if (skip_comments && len && buffer[i] == '#') {
55 newlen = cleanup(buffer + i, len);
57 /* Not just an empty line? */
64 memmove(buffer + j, buffer + i, newlen);
75 int cmd_stripspace(int argc, const char **argv, const char *prefix)
79 int strip_comments = 0;
81 if (argc > 1 && (!strcmp(argv[1], "-s") ||
82 !strcmp(argv[1], "--strip-comments")))
86 buffer = xmalloc(size);
87 if (read_fd(0, &buffer, &size)) {
89 die("could not read the input");
92 size = stripspace(buffer, size, strip_comments);
93 write_or_die(1, buffer, size);