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 -n 2 hands the input to a command two items at a time

Xargs
~/tips/tip-xargs-n-2-pairs

printf 'old1.txt new1.txt\nold2.txt new2.txt\n' | xargs -n 2 mv

Splits a list into fixed-size groups, so each command run gets exactly the number of arguments it needs.

By default xargs stuffs as many items as fit into one command. Some commands want a fixed number of arguments per call, like an old name and a new name. -n sets that number.

printf 'old1.txt new1.txt\nold2.txt new2.txt\n' | xargs -n 2 mv

xargs reads all words from the input and runs mv once per pair: mv old1.txt new1.txt, then mv old2.txt new2.txt. Put echo mv in front first, which prints the commands instead of running them; I’d make that a habit for anything that renames or deletes.

-n 1 is the other common use: one run per item, for commands that only accept a single argument, like some older tools or scripts.

It counts words, not lines. A file name with a space in it is two words to xargs, so the pairs shift and the wrong files get renamed. That’s the risky part of this trick. For names with spaces, put each name on its own line and add -d '\n', so a line is one item:

printf '%s\n' 'my old.txt' 'my new.txt' | xargs -d '\n' -n 2 mv

And if the input has an odd number of items, the last run gets only one argument. mv then complains, but other commands might do something you didn’t intend.

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 'a b\nc d\n' | xargs -L 1 echo line: All Xargs tips (12) All topics

Link