GNU head
and tail
since coreutils version 8.25 have a -z
option for that.
With older versions or for non-GNU systems, you can try and swap \0
and \n
:
find ... -print0 |
tr '\0\n' '\n\0' |
head |
tr '\0\n' '\n\0'
Note that some head
implementations can't cope with NUL characters (and they're not required to by POSIX), but where find supports -print0
, head
and text utilities generally support NUL characters.
You can also use a function to wrap any command between the two tr
s:
nul_terminated() {
tr '\0\n' '\n\0' | "$@" | tr '\0\n' '\n\0'
}
find ... -print0 | nul_terminated tail -n 12 | xargs -r0 ...
Keep in mind that under nul_terminated
, a \0
means a newline character. So for instance, to replace \n
with _
:
find . -depth -name $'*\n*' -print0 | nul_terminated sed '
p;h;s,.*/,,;s/\x0/_/g;H;g;s,[^/]*\n,,' | xargs -r0n2 mv
(\x0
being also a GNU extension).
If you need to run more than one filtering command, you can do:
find ... -print0 |
nul_terminated cmd1 |
nul_terminated cmd2 | xargs -r0 ...
But that means running a few redundant tr
commands. Alternatively, you can run:
find ... -print0 | nul_terminated eval 'cmd1 | cmd2' | xargs -r0 ...
Best Answer
If you want that last 10 lines:
But with GNU
xargs
, you can also set the delimiter to newline with:(
-0
is short for-d '\0'
).Portably, you can also simply escape every character:
Or quote each line:
If you want the 10 last NUL-delimited records of
myFile.txt
(but then that wouldn't be a text file), you'd have to convert the\n
to\0
before callingtail
which would mean the file will have to be read fully:Edit (since you changed the
tail
totail -f
in your question):The last one above obviously doesn't make sense for
tail -f
.The
xargs -d '\n'
one will work, but for the other ones, you'll have a buffering problem. In:tr
buffers its output when it doesn't go to a terminal (here, a pipe). I.E., it will not write anything until it has accumulated a buffer full (something like 8kiB) of data to write. Which meansmyCmd
will be called in batches.On a GNU or FreeBSD system, you can alter the buffering behavior of
tr
with thestdbuf
command: