brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: xargs -L 1 runs one command per input line, not per word

Xargs
~/tips/tip-xargs-l-1-per-line

printf 'a b\nc d\n' | xargs -L 1 echo line:

Keeps each input line together as the arguments of one command run.

-n 1 runs a command per word. When each line of input is a complete set of arguments, you want one run per line, and that’s -L 1.

printf 'a b\nc d\n' | xargs -L 1 echo line:

This prints line: a b and line: c d. With -n 1 the same input gives four runs, one for each letter. A list of user and group pairs for chown, or a file with source target per line, is where I’d reach for -L 1.

There’s a strange rule hidden in it. A line that ends with a space or tab continues on the next line. So a b with a trailing space followed by c d comes out as one run, line: a b c d. Files edited by hand often have trailing spaces you can’t see, so that can glue lines together in a way that’s hard to spot.

Words inside a line are still split on blanks and quotes are still special, so a line with a file name containing a space gives that command an extra argument. If what you need is one whole line as one single argument, -d '\n' combined with -n 1 is the right tool, and that one doesn’t have the trailing space rule either.

Further reading: xargs(1) manual page, GNU findutils manual: Invoking xargs

More Xargs tips printf '%s\n' a b c d e f | xargs -n1 -P3 --process-slot-var=SLOT sh -c 'echo "slot $SLOT got $0"; sleep 0.2' grep -l 'TODO' *.py | xargs -o vim find . -name '*.orig' -print0 | xargs -0 -p rm find . -name '*.gz' -print0 | xargs -0 -n 1 gzip -t printf 'x\ny\n' | xargs -t touch All Xargs tips (12) All topics

Link