Let's say, I run a find command without xargs

find . -iname 'connect*' > cat output.txt

Question:1. How to copy the output of find command to a text file using xargs command? 2. What is advantage here on using the xargs command instead of just using >

I tried the below one and it doesnt seems to be correct.

find . -iname 'connect*'  | xargs -t cat > output.txt
  • Are you trying to concatenate the names of the files, or their contents? – steeldriver Jul 8 '17 at 15:20

xargs takes strings from stdin and a command line on its own command line. It runs the command line using the strings from stdin as arguments to the command line. It's basically doing indirection. If you have a list of filenames (such as find produces) you can performa operations on the individual files (or their contents) with xargs. Like getting a top-20 word frequency list from a number of text files:

find . -name '*.txt' | xargs cat | tr -s '[:blank:]' '\n' | sort | uniq -c | sort -k1.1nr | head -20

I'm not sure it's worthwhile to perform your task from Question 1. I'm certain that it can be done, but why bother? And that's the answer to question 2: there is no advantage either in performance or clarity of intention.

In general, the advantage of using xargs is that you can do elaborate things to decide which file names to put on its stdin. Your find could have time-of-creation added to it, or more than one name glob, or whatever. Just having a static list of filenames negates any advantage you might get from xargs: you'd be better off using cat or running the command xargs would run in a loop.

  • 1
    It breaks if you have a file like: 2"x4" lumber.txt. This problem was the initial reason for building GNU Parallel. – Ole Tange Apr 24 '18 at 20:21

xargs helps you to execute commands on lines of the output like:

find . -name '*.mp3' | xargs mp3info

for every file found by find (i.e. output line)

mp3info <filename>

is executed

If you want to do something with the whole output of find, you don't need xargs at all.

  • If you have a file called 12" record from 1" tape.mp3 the above will fail. Substitute xargs with parallel and it will work. – Ole Tange Apr 24 '18 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.