1 /* paste - merge lines of files
2 Copyright (C) 1997-2005, 2008 Free Software Foundation, Inc.
3 Copyright (C) 1984 David M. Ihnat
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Written by David Ihnat. */
20 /* The list of valid escape sequences has been expanded over the Unix
21 version, to include \b, \f, \r, and \v.
23 POSIX changes, bug fixes, long-named options, and cleanup
24 by David MacKenzie <djm@gnu.ai.mit.edu>.
28 -s Paste one file at a time rather than
29 one line from each file.
30 --delimiters=delim-list
31 -d delim-list Consecutively use the characters in
32 DELIM-LIST instead of tab to separate
33 merged lines. When DELIM-LIST is exhausted,
34 start again at its beginning.
35 A FILE of `-' means standard input.
36 If no FILEs are given, standard input is used. */
42 #include <sys/types.h>
47 /* The official name of this program (e.g., no `g' prefix). */
48 #define PROGRAM_NAME "paste"
51 proper_name ("David M. Ihnat"), \
52 proper_name ("David MacKenzie")
54 /* Indicates that no delimiter should be added in the current position. */
55 #define EMPTY_DELIM '\0'
57 /* Name this program was run with. */
60 /* If nonzero, we have read standard input at some point. */
61 static bool have_read_stdin;
63 /* If nonzero, merge subsequent lines of each file rather than
64 corresponding lines from each file in parallel. */
65 static bool serial_merge;
67 /* The delimeters between lines of input files (used cyclically). */
70 /* A pointer to the character after the end of `delims'. */
71 static char const *delim_end;
73 static struct option const longopts[] =
75 {"serial", no_argument, NULL, 's'},
76 {"delimiters", required_argument, NULL, 'd'},
77 {GETOPT_HELP_OPTION_DECL},
78 {GETOPT_VERSION_OPTION_DECL},
82 /* Set globals delims and delim_end. Copy STRPTR to DELIMS, converting
83 backslash representations of special characters in STRPTR to their actual
84 values. The set of possible backslash characters has been expanded beyond
85 that recognized by the Unix version.
86 Return 0 upon success.
87 If the string ends in an odd number of backslashes, ignore the
88 final backslash and return nonzero. */
91 collapse_escapes (char const *strptr)
93 char *strout = xstrdup (strptr);
94 bool backslash_at_end = false;
100 if (*strptr != '\\') /* Is it an escape character? */
101 *strout++ = *strptr++; /* No, just transfer it. */
107 *strout++ = EMPTY_DELIM;
139 backslash_at_end = true;
153 return backslash_at_end ? 1 : 0;
156 /* Report a write error and exit. */
158 static void write_error (void) ATTRIBUTE_NORETURN;
162 error (EXIT_FAILURE, errno, _("write error"));
166 /* Output a single byte, reporting any write errors. */
175 /* Perform column paste on the NFILES files named in FNAMPTR.
176 Return true if successful, false if one or more files could not be
180 paste_parallel (size_t nfiles, char **fnamptr)
183 /* If all files are just ready to be closed, or will be on this
184 round, the string of delimiters must be preserved.
185 delbuf[0] through delbuf[nfiles]
186 store the delimiters for closed files. */
187 char *delbuf = xmalloc (nfiles + 2);
189 /* Streams open to the files to process; NULL if the corresponding
191 FILE **fileptr = xnmalloc (nfiles + 1, sizeof *fileptr);
193 /* Number of files still open to process. */
196 /* True if any fopen got fd == STDIN_FILENO. */
197 bool opened_stdin = false;
199 /* Attempt to open all files. This could be expanded to an infinite
200 number of files, but at the (considerable) expense of remembering
201 each file and its current offset, then opening/reading/closing. */
203 for (files_open = 0; files_open < nfiles; ++files_open)
205 if (STREQ (fnamptr[files_open], "-"))
207 have_read_stdin = true;
208 fileptr[files_open] = stdin;
212 fileptr[files_open] = fopen (fnamptr[files_open], "r");
213 if (fileptr[files_open] == NULL)
214 error (EXIT_FAILURE, errno, "%s", fnamptr[files_open]);
215 else if (fileno (fileptr[files_open]) == STDIN_FILENO)
220 if (opened_stdin && have_read_stdin)
221 error (EXIT_FAILURE, 0, _("standard input is closed"));
223 /* Read a line from each file and output it to stdout separated by a
224 delimiter, until we go through the loop without successfully
225 reading from any of the files. */
229 /* Set up for the next line. */
230 bool somedone = false;
231 char const *delimptr = delims;
232 size_t delims_saved = 0; /* Number of delims saved in `delbuf'. */
235 for (i = 0; i < nfiles && files_open; i++)
237 int chr IF_LINT (= 0); /* Input character. */
238 int err IF_LINT (= 0); /* Input errno value. */
239 size_t line_length = 0; /* Number of chars in line. */
243 chr = getc (fileptr[i]);
245 if (chr != EOF && delims_saved)
247 if (fwrite (delbuf, 1, delims_saved, stdout) != delims_saved)
258 chr = getc (fileptr[i]);
263 if (line_length == 0)
265 /* EOF, read error, or closed file.
266 If an EOF or error, close the file. */
269 if (ferror (fileptr[i]))
271 error (0, err, "%s", fnamptr[i]);
274 if (fileptr[i] == stdin)
275 clearerr (fileptr[i]); /* Also clear EOF. */
276 else if (fclose (fileptr[i]) == EOF)
278 error (0, errno, "%s", fnamptr[i]);
288 /* End of this output line.
289 Is this the end of the whole thing? */
292 /* No. Some files were not closed for this line. */
295 if (fwrite (delbuf, 1, delims_saved, stdout)
302 continue; /* Next read of files, or exit. */
306 /* Closed file; add delimiter to `delbuf'. */
307 if (*delimptr != EMPTY_DELIM)
308 delbuf[delims_saved++] = *delimptr;
309 if (++delimptr == delim_end)
315 /* Some data read. */
318 /* Except for last file, replace last newline with delim. */
321 if (chr != '\n' && chr != EOF)
323 if (*delimptr != EMPTY_DELIM)
324 xputchar (*delimptr);
325 if (++delimptr == delim_end)
330 /* If the last line of the last file lacks a newline,
331 print one anyhow. POSIX requires this. */
332 char c = (chr == EOF ? '\n' : chr);
343 /* Perform serial paste on the NFILES files named in FNAMPTR.
344 Return true if no errors, false if one or more files could not be
348 paste_serial (size_t nfiles, char **fnamptr)
350 bool ok = true; /* false if open or read errors occur. */
351 int charnew, charold; /* Current and previous char read. */
352 char const *delimptr; /* Current delimiter char. */
353 FILE *fileptr; /* Open for reading current file. */
355 for (; nfiles; nfiles--, fnamptr++)
358 bool is_stdin = STREQ (*fnamptr, "-");
361 have_read_stdin = true;
366 fileptr = fopen (*fnamptr, "r");
369 error (0, errno, "%s", *fnamptr);
375 delimptr = delims; /* Set up for delimiter string. */
377 charold = getc (fileptr);
381 /* `charold' is set up. Hit it!
382 Keep reading characters, stashing them in `charnew';
383 output `charold', converting to the appropriate delimiter
384 character if needed. After the EOF, output `charold'
385 if it's a newline; otherwise, output it and then a newline. */
387 while ((charnew = getc (fileptr)) != EOF)
389 /* Process the old character. */
392 if (*delimptr != EMPTY_DELIM)
393 xputchar (*delimptr);
395 if (++delimptr == delim_end)
405 /* Hit EOF. Process that last character. */
412 if (ferror (fileptr))
414 error (0, saved_errno, "%s", *fnamptr);
418 clearerr (fileptr); /* Also clear EOF. */
419 else if (fclose (fileptr) == EOF)
421 error (0, errno, "%s", *fnamptr);
431 if (status != EXIT_SUCCESS)
432 fprintf (stderr, _("Try `%s --help' for more information.\n"),
437 Usage: %s [OPTION]... [FILE]...\n\
441 Write lines consisting of the sequentially corresponding lines from\n\
442 each FILE, separated by TABs, to standard output.\n\
443 With no FILE, or when FILE is -, read standard input.\n\
447 Mandatory arguments to long options are mandatory for short options too.\n\
450 -d, --delimiters=LIST reuse characters from LIST instead of TABs\n\
451 -s, --serial paste one file at a time instead of in parallel\n\
453 fputs (HELP_OPTION_DESCRIPTION, stdout);
454 fputs (VERSION_OPTION_DESCRIPTION, stdout);
455 /* FIXME: add a couple of examples. */
456 emit_bug_reporting_address ();
462 main (int argc, char **argv)
466 char const *delim_arg = "\t";
468 initialize_main (&argc, &argv);
469 program_name = argv[0];
470 setlocale (LC_ALL, "");
471 bindtextdomain (PACKAGE, LOCALEDIR);
472 textdomain (PACKAGE);
474 atexit (close_stdout);
476 have_read_stdin = false;
477 serial_merge = false;
479 while ((optc = getopt_long (argc, argv, "d:s", longopts, NULL)) != -1)
484 /* Delimiter character(s). */
485 delim_arg = (optarg[0] == '\0' ? "\\0" : optarg);
492 case_GETOPT_HELP_CHAR;
494 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
497 usage (EXIT_FAILURE);
504 if (collapse_escapes (delim_arg))
506 /* Don't use the default quoting style, because that would double the
507 number of displayed backslashes, making the diagnostic look bogus. */
508 set_quoting_style (NULL, escape_quoting_style);
509 error (EXIT_FAILURE, 0,
510 _("delimiter list ends with an unescaped backslash: %s"),
511 quotearg_colon (delim_arg));
515 ok = paste_parallel (argc - optind, &argv[optind]);
517 ok = paste_serial (argc - optind, &argv[optind]);
521 if (have_read_stdin && fclose (stdin) == EOF)
522 error (EXIT_FAILURE, errno, "-");
523 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);