cut.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. /* cut - remove parts of lines of files
  2. Copyright (C) 1997-2018 Free Software Foundation, Inc.
  3. Copyright (C) 1984 David M. Ihnat
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. /* Written by David Ihnat. */
  15. /* POSIX changes, bug fixes, long-named options, and cleanup
  16. by David MacKenzie <djm@gnu.ai.mit.edu>.
  17. Rewrite cut_fields and cut_bytes -- Jim Meyering. */
  18. #include <config.h>
  19. #include <stdio.h>
  20. #include <assert.h>
  21. #include <getopt.h>
  22. #include <sys/types.h>
  23. #include "system.h"
  24. #include "error.h"
  25. #include "fadvise.h"
  26. #include "getndelim2.h"
  27. #include "hash.h"
  28. #include "xstrndup.h"
  29. #include "set-fields.h"
  30. /* The official name of this program (e.g., no 'g' prefix). */
  31. #define PROGRAM_NAME "cut"
  32. #define AUTHORS \
  33. proper_name ("David M. Ihnat"), \
  34. proper_name ("David MacKenzie"), \
  35. proper_name ("Jim Meyering")
  36. #define FATAL_ERROR(Message) \
  37. do \
  38. { \
  39. error (0, 0, (Message)); \
  40. usage (EXIT_FAILURE); \
  41. } \
  42. while (0)
  43. /* Pointer inside RP. When checking if a byte or field is selected
  44. by a finite range, we check if it is between CURRENT_RP.LO
  45. and CURRENT_RP.HI. If the byte or field index is greater than
  46. CURRENT_RP.HI then we make CURRENT_RP to point to the next range pair. */
  47. static struct field_range_pair *current_rp;
  48. /* This buffer is used to support the semantics of the -s option
  49. (or lack of same) when the specified field list includes (does
  50. not include) the first field. In both of those cases, the entire
  51. first field must be read into this buffer to determine whether it
  52. is followed by a delimiter or a newline before any of it may be
  53. output. Otherwise, cut_fields can do the job without using this
  54. buffer. */
  55. static char *field_1_buffer;
  56. /* The number of bytes allocated for FIELD_1_BUFFER. */
  57. static size_t field_1_bufsize;
  58. enum operating_mode
  59. {
  60. undefined_mode,
  61. /* Output characters that are in the given bytes. */
  62. byte_mode,
  63. /* Output the given delimiter-separated fields. */
  64. field_mode
  65. };
  66. static enum operating_mode operating_mode;
  67. /* If true do not output lines containing no delimiter characters.
  68. Otherwise, all such lines are printed. This option is valid only
  69. with field mode. */
  70. static bool suppress_non_delimited;
  71. /* If true, print all bytes, characters, or fields _except_
  72. those that were specified. */
  73. static bool complement;
  74. /* The delimiter character for field mode. */
  75. static unsigned char delim;
  76. /* The delimiter for each line/record. */
  77. static unsigned char line_delim = '\n';
  78. /* True if the --output-delimiter=STRING option was specified. */
  79. static bool output_delimiter_specified;
  80. /* The length of output_delimiter_string. */
  81. static size_t output_delimiter_length;
  82. /* The output field separator string. Defaults to the 1-character
  83. string consisting of the input delimiter. */
  84. static char *output_delimiter_string;
  85. /* True if we have ever read standard input. */
  86. static bool have_read_stdin;
  87. /* For long options that have no equivalent short option, use a
  88. non-character as a pseudo short option, starting with CHAR_MAX + 1. */
  89. enum
  90. {
  91. OUTPUT_DELIMITER_OPTION = CHAR_MAX + 1,
  92. COMPLEMENT_OPTION
  93. };
  94. static struct option const longopts[] =
  95. {
  96. {"bytes", required_argument, NULL, 'b'},
  97. {"characters", required_argument, NULL, 'c'},
  98. {"fields", required_argument, NULL, 'f'},
  99. {"delimiter", required_argument, NULL, 'd'},
  100. {"only-delimited", no_argument, NULL, 's'},
  101. {"output-delimiter", required_argument, NULL, OUTPUT_DELIMITER_OPTION},
  102. {"complement", no_argument, NULL, COMPLEMENT_OPTION},
  103. {"zero-terminated", no_argument, NULL, 'z'},
  104. {GETOPT_HELP_OPTION_DECL},
  105. {GETOPT_VERSION_OPTION_DECL},
  106. {NULL, 0, NULL, 0}
  107. };
  108. void
  109. usage (int status)
  110. {
  111. if (status != EXIT_SUCCESS)
  112. emit_try_help ();
  113. else
  114. {
  115. printf (_("\
  116. Usage: %s OPTION... [FILE]...\n\
  117. "),
  118. program_name);
  119. fputs (_("\
  120. Print selected parts of lines from each FILE to standard output.\n\
  121. "), stdout);
  122. emit_stdin_note ();
  123. emit_mandatory_arg_note ();
  124. fputs (_("\
  125. -b, --bytes=LIST select only these bytes\n\
  126. -c, --characters=LIST select only these characters\n\
  127. -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter\n\
  128. "), stdout);
  129. fputs (_("\
  130. -f, --fields=LIST select only these fields; also print any line\n\
  131. that contains no delimiter character, unless\n\
  132. the -s option is specified\n\
  133. -n (ignored)\n\
  134. "), stdout);
  135. fputs (_("\
  136. --complement complement the set of selected bytes, characters\n\
  137. or fields\n\
  138. "), stdout);
  139. fputs (_("\
  140. -s, --only-delimited do not print lines not containing delimiters\n\
  141. --output-delimiter=STRING use STRING as the output delimiter\n\
  142. the default is to use the input delimiter\n\
  143. "), stdout);
  144. fputs (_("\
  145. -z, --zero-terminated line delimiter is NUL, not newline\n\
  146. "), stdout);
  147. fputs (HELP_OPTION_DESCRIPTION, stdout);
  148. fputs (VERSION_OPTION_DESCRIPTION, stdout);
  149. fputs (_("\
  150. \n\
  151. Use one, and only one of -b, -c or -f. Each LIST is made up of one\n\
  152. range, or many ranges separated by commas. Selected input is written\n\
  153. in the same order that it is read, and is written exactly once.\n\
  154. "), stdout);
  155. fputs (_("\
  156. Each range is one of:\n\
  157. \n\
  158. N N'th byte, character or field, counted from 1\n\
  159. N- from N'th byte, character or field, to end of line\n\
  160. N-M from N'th to M'th (included) byte, character or field\n\
  161. -M from first to M'th (included) byte, character or field\n\
  162. "), stdout);
  163. emit_ancillary_info (PROGRAM_NAME);
  164. }
  165. exit (status);
  166. }
  167. /* Increment *ITEM_IDX (i.e., a field or byte index),
  168. and if required CURRENT_RP. */
  169. static inline void
  170. next_item (uintmax_t *item_idx)
  171. {
  172. (*item_idx)++;
  173. if ((*item_idx) > current_rp->hi)
  174. current_rp++;
  175. }
  176. /* Return nonzero if the K'th field or byte is printable. */
  177. static inline bool
  178. print_kth (uintmax_t k)
  179. {
  180. return current_rp->lo <= k;
  181. }
  182. /* Return nonzero if K'th byte is the beginning of a range. */
  183. static inline bool
  184. is_range_start_index (uintmax_t k)
  185. {
  186. return k == current_rp->lo;
  187. }
  188. /* Read from stream STREAM, printing to standard output any selected bytes. */
  189. static void
  190. cut_bytes (FILE *stream)
  191. {
  192. uintmax_t byte_idx; /* Number of bytes in the line so far. */
  193. /* Whether to begin printing delimiters between ranges for the current line.
  194. Set after we've begun printing data corresponding to the first range. */
  195. bool print_delimiter;
  196. byte_idx = 0;
  197. print_delimiter = false;
  198. current_rp = frp;
  199. while (true)
  200. {
  201. int c; /* Each character from the file. */
  202. c = getc (stream);
  203. if (c == line_delim)
  204. {
  205. putchar (c);
  206. byte_idx = 0;
  207. print_delimiter = false;
  208. current_rp = frp;
  209. }
  210. else if (c == EOF)
  211. {
  212. if (byte_idx > 0)
  213. putchar (line_delim);
  214. break;
  215. }
  216. else
  217. {
  218. next_item (&byte_idx);
  219. if (print_kth (byte_idx))
  220. {
  221. if (output_delimiter_specified)
  222. {
  223. if (print_delimiter && is_range_start_index (byte_idx))
  224. {
  225. fwrite (output_delimiter_string, sizeof (char),
  226. output_delimiter_length, stdout);
  227. }
  228. print_delimiter = true;
  229. }
  230. putchar (c);
  231. }
  232. }
  233. }
  234. }
  235. /* Read from stream STREAM, printing to standard output any selected fields. */
  236. static void
  237. cut_fields (FILE *stream)
  238. {
  239. int c;
  240. uintmax_t field_idx = 1;
  241. bool found_any_selected_field = false;
  242. bool buffer_first_field;
  243. current_rp = frp;
  244. c = getc (stream);
  245. if (c == EOF)
  246. return;
  247. ungetc (c, stream);
  248. c = 0;
  249. /* To support the semantics of the -s flag, we may have to buffer
  250. all of the first field to determine whether it is 'delimited.'
  251. But that is unnecessary if all non-delimited lines must be printed
  252. and the first field has been selected, or if non-delimited lines
  253. must be suppressed and the first field has *not* been selected.
  254. That is because a non-delimited line has exactly one field. */
  255. buffer_first_field = (suppress_non_delimited ^ !print_kth (1));
  256. while (1)
  257. {
  258. if (field_idx == 1 && buffer_first_field)
  259. {
  260. ssize_t len;
  261. size_t n_bytes;
  262. len = getndelim2 (&field_1_buffer, &field_1_bufsize, 0,
  263. GETNLINE_NO_LIMIT, delim, line_delim, stream);
  264. if (len < 0)
  265. {
  266. free (field_1_buffer);
  267. field_1_buffer = NULL;
  268. if (ferror (stream) || feof (stream))
  269. break;
  270. xalloc_die ();
  271. }
  272. n_bytes = len;
  273. assert (n_bytes != 0);
  274. c = 0;
  275. /* If the first field extends to the end of line (it is not
  276. delimited) and we are printing all non-delimited lines,
  277. print this one. */
  278. if (to_uchar (field_1_buffer[n_bytes - 1]) != delim)
  279. {
  280. if (suppress_non_delimited)
  281. {
  282. /* Empty. */
  283. }
  284. else
  285. {
  286. fwrite (field_1_buffer, sizeof (char), n_bytes, stdout);
  287. /* Make sure the output line is newline terminated. */
  288. if (field_1_buffer[n_bytes - 1] != line_delim)
  289. putchar (line_delim);
  290. c = line_delim;
  291. }
  292. continue;
  293. }
  294. if (print_kth (1))
  295. {
  296. /* Print the field, but not the trailing delimiter. */
  297. fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout);
  298. /* With -d$'\n' don't treat the last '\n' as a delimiter. */
  299. if (delim == line_delim)
  300. {
  301. int last_c = getc (stream);
  302. if (last_c != EOF)
  303. {
  304. ungetc (last_c, stream);
  305. found_any_selected_field = true;
  306. }
  307. }
  308. else
  309. found_any_selected_field = true;
  310. }
  311. next_item (&field_idx);
  312. }
  313. int prev_c = c;
  314. if (print_kth (field_idx))
  315. {
  316. if (found_any_selected_field)
  317. {
  318. fwrite (output_delimiter_string, sizeof (char),
  319. output_delimiter_length, stdout);
  320. }
  321. found_any_selected_field = true;
  322. while ((c = getc (stream)) != delim && c != line_delim && c != EOF)
  323. {
  324. putchar (c);
  325. prev_c = c;
  326. }
  327. }
  328. else
  329. {
  330. while ((c = getc (stream)) != delim && c != line_delim && c != EOF)
  331. {
  332. prev_c = c;
  333. }
  334. }
  335. /* With -d$'\n' don't treat the last '\n' as a delimiter. */
  336. if (delim == line_delim && c == delim)
  337. {
  338. int last_c = getc (stream);
  339. if (last_c != EOF)
  340. ungetc (last_c, stream);
  341. else
  342. c = last_c;
  343. }
  344. if (c == delim)
  345. next_item (&field_idx);
  346. else if (c == line_delim || c == EOF)
  347. {
  348. if (found_any_selected_field
  349. || !(suppress_non_delimited && field_idx == 1))
  350. {
  351. if (c == line_delim || prev_c != line_delim
  352. || delim == line_delim)
  353. putchar (line_delim);
  354. }
  355. if (c == EOF)
  356. break;
  357. field_idx = 1;
  358. current_rp = frp;
  359. found_any_selected_field = false;
  360. }
  361. }
  362. }
  363. static void
  364. cut_stream (FILE *stream)
  365. {
  366. if (operating_mode == byte_mode)
  367. cut_bytes (stream);
  368. else
  369. cut_fields (stream);
  370. }
  371. /* Process file FILE to standard output.
  372. Return true if successful. */
  373. static bool
  374. cut_file (char const *file)
  375. {
  376. FILE *stream;
  377. if (STREQ (file, "-"))
  378. {
  379. have_read_stdin = true;
  380. stream = stdin;
  381. }
  382. else
  383. {
  384. stream = fopen (file, "r");
  385. if (stream == NULL)
  386. {
  387. error (0, errno, "%s", quotef (file));
  388. return false;
  389. }
  390. }
  391. fadvise (stream, FADVISE_SEQUENTIAL);
  392. cut_stream (stream);
  393. if (ferror (stream))
  394. {
  395. error (0, errno, "%s", quotef (file));
  396. return false;
  397. }
  398. if (STREQ (file, "-"))
  399. clearerr (stream); /* Also clear EOF. */
  400. else if (fclose (stream) == EOF)
  401. {
  402. error (0, errno, "%s", quotef (file));
  403. return false;
  404. }
  405. return true;
  406. }
  407. int
  408. main (int argc, char **argv)
  409. {
  410. int optc;
  411. bool ok;
  412. bool delim_specified = false;
  413. char *spec_list_string IF_LINT ( = NULL);
  414. initialize_main (&argc, &argv);
  415. set_program_name (argv[0]);
  416. setlocale (LC_ALL, "");
  417. bindtextdomain (PACKAGE, LOCALEDIR);
  418. textdomain (PACKAGE);
  419. atexit (close_stdout);
  420. operating_mode = undefined_mode;
  421. /* By default, all non-delimited lines are printed. */
  422. suppress_non_delimited = false;
  423. delim = '\0';
  424. have_read_stdin = false;
  425. while ((optc = getopt_long (argc, argv, "b:c:d:f:nsz", longopts, NULL)) != -1)
  426. {
  427. switch (optc)
  428. {
  429. case 'b':
  430. case 'c':
  431. /* Build the byte list. */
  432. if (operating_mode != undefined_mode)
  433. FATAL_ERROR (_("only one type of list may be specified"));
  434. operating_mode = byte_mode;
  435. spec_list_string = optarg;
  436. break;
  437. case 'f':
  438. /* Build the field list. */
  439. if (operating_mode != undefined_mode)
  440. FATAL_ERROR (_("only one type of list may be specified"));
  441. operating_mode = field_mode;
  442. spec_list_string = optarg;
  443. break;
  444. case 'd':
  445. /* New delimiter. */
  446. /* Interpret -d '' to mean 'use the NUL byte as the delimiter.' */
  447. if (optarg[0] != '\0' && optarg[1] != '\0')
  448. FATAL_ERROR (_("the delimiter must be a single character"));
  449. delim = optarg[0];
  450. delim_specified = true;
  451. break;
  452. case OUTPUT_DELIMITER_OPTION:
  453. output_delimiter_specified = true;
  454. /* Interpret --output-delimiter='' to mean
  455. 'use the NUL byte as the delimiter.' */
  456. output_delimiter_length = (optarg[0] == '\0'
  457. ? 1 : strlen (optarg));
  458. output_delimiter_string = xstrdup (optarg);
  459. break;
  460. case 'n':
  461. break;
  462. case 's':
  463. suppress_non_delimited = true;
  464. break;
  465. case 'z':
  466. line_delim = '\0';
  467. break;
  468. case COMPLEMENT_OPTION:
  469. complement = true;
  470. break;
  471. case_GETOPT_HELP_CHAR;
  472. case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
  473. default:
  474. usage (EXIT_FAILURE);
  475. }
  476. }
  477. if (operating_mode == undefined_mode)
  478. FATAL_ERROR (_("you must specify a list of bytes, characters, or fields"));
  479. if (delim_specified && operating_mode != field_mode)
  480. FATAL_ERROR (_("an input delimiter may be specified only\
  481. when operating on fields"));
  482. if (suppress_non_delimited && operating_mode != field_mode)
  483. FATAL_ERROR (_("suppressing non-delimited lines makes sense\n\
  484. \tonly when operating on fields"));
  485. set_fields (spec_list_string,
  486. ( (operating_mode == field_mode) ? 0 : SETFLD_ERRMSG_USE_POS)
  487. | (complement ? SETFLD_COMPLEMENT : 0) );
  488. if (!delim_specified)
  489. delim = '\t';
  490. if (output_delimiter_string == NULL)
  491. {
  492. static char dummy[2];
  493. dummy[0] = delim;
  494. dummy[1] = '\0';
  495. output_delimiter_string = dummy;
  496. output_delimiter_length = 1;
  497. }
  498. if (optind == argc)
  499. ok = cut_file ("-");
  500. else
  501. for (ok = true; optind < argc; optind++)
  502. ok &= cut_file (argv[optind]);
  503. if (have_read_stdin && fclose (stdin) == EOF)
  504. {
  505. error (0, errno, "-");
  506. ok = false;
  507. }
  508. IF_LINT (reset_fields ());
  509. return ok ? EXIT_SUCCESS : EXIT_FAILURE;
  510. }