custom delimiter for unix find results

I want to use find to find some files, and return all files as a single line (without newline characters), and a custom delimiter between the files.

So for example the result for three files would be

/my/file/1::/my/file/2::/my/file/3

instead of

/my/file/1
/my/file/2
/my/file/3

Is there any way of achieving this using standard unix tools in combination with find?

Asked By: muffel

||

With the GNU implementation of find and sed, you can use :

find . -type f -printf '%p::' | sed '$s/::$/n/'
  • The -printf predicate of GNU find will print the file names in a single line delimited by :: and then sed will substitute the last :: on the last (here undelimited) line with a newline.

Example :

$ find . -type f -printf '%pn'
./foo
./test file
whose name
contains newline characters and ::
./bar

$ find . -type f -printf '%p::' | sed '$s/::$/n/'
./foo::./test file
whose name
contains newline characters and ::::./bar

The standard equivalent of -printf '%p::' would be -exec printf '%s::' {} +. There is no equivalent for that GNU sed expression as POSIX sed cannot handle non-text.

Answered By: heemayl

You won’t find -prinf in many find implementations. For those cases you can achieve the same by using the -exec command.

find "/some/dir" -exec echo -n {}"|" ;

echo prints every dir entry

The -n modifier avoids printing a new line character

The "|" character is appended after every entry

If your echo implementation does not support the -n flag, simple:

find "/some/dir" -exec printf "%s" {}"|" ;

The above will work in virtually any bash shell, including busybox which is present in minimalistic firmware oriented distros like OpenWRT or VMWare ESXi.

(*) Please, note that the printf call in the last example is external to find and not a find option as is posed in the first answer. printf as a binary is present in almost any distro you can think of, even the smallest ones.

Answered By: Daniel J.

With zsh:

(){ print -r -- ${(j[::])argv}; } /my/**/*(N.)

To find all the regular non-hidden files under /my/ and print their paths (sorted lexically, though see the n, o and O qualifiers for alternative sorting orders) joined with ::.

Answered By: Stéphane Chazelas
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.