0

I've got that far: wc --files0-from=FILE lets one get the word count of a list of files. Each entry in this list mus be terminated with an ASCII NUL character.

Question: A way to set a terminating character, such as NUL by hand, or something else? I found this here [quoted from the info wc output]:

… produce a list of ASCII NUL terminated file names is with GNU find', using its-print0' predicate.

I found somebody saying the each file name is being terminated by an ASCII NUL character. Is it right that this fits to, say the output of ls? I know, one shouldn't parse ls, but writing the output into a file to be read by wc another time would be nice.

erch
  • 5,030
  • 2
    http://unix.stackexchange.com/questions/2722/can-i-determine-the-number-of-sub-directories-in-a-directory-using-ls-l/20858#20858. In this answer, each filename is terminated by a NUL because of the printf command. printf '%s\000' * takes the files in the current directory (thanks to '*') and prints each one appending a \000 (a NUL character) after it. – lgeorget Jun 16 '13 at 21:48
  • wc --files0-from=<(find . -type f -print0) – Nykakin Jun 17 '13 at 00:41

1 Answers1

6

ls ends each filename with a newline (\n) and not a NUL (\0) (if its standard output is not a terminal).

A way to list the files in the current directory, using NUL as a separator, is:

find . -maxdepth 1 -print0.

This will match the files starting with a period too. To ignore them, use:

find . -maxdepth 1 \! -name '.*' -print0

Others ways could be:

ls | tr '\n' '\0'

or

printf '%s\0' *

As noted by @ChrisDown in his comment, only the find and the printf options will do the job correctly if you have file names containing \n in the current directory. If this is not your case (in fact, I wonder if there really are people using newlines in file names out there), the three are equivalent.

lgeorget
  • 13,914
  • 4
    Note that ls | tr '\n' '\0' and find . -maxdepth 1 \! -name '.*' -print0 are not strictly equivalent as the former will mangle existing newlines that are not terminators: http://sprunge.us/MMYj – Chris Down Jun 17 '13 at 03:45
  • 1
    If you want to exclude the current directory but include hidden files, use -mindepth 1. – l0b0 Jun 17 '13 at 09:28
  • 1
    @ChrisDown Yes, you're right. find is the only command that will function well with all valid filenames. The ls solution will work in most of the cases, but not all. @l0b0 Great! Thank you for the -mindepth precision. – lgeorget Jun 17 '13 at 11:51