You can also pipe find to the xargs command
The bare snippets from - http://www.unixmantra.com/2013/12/xargs-all-in-one-tutorial-guide.html
Find all the .mp3 files in the music folder and pass to the ls command, -print0 is required if any filenames contain whitespace.:
find ./music -name "*.mp3" -print0 | xargs -0 ls
Find all files in the work folder, pass to grep and search for profit:
find ./work -print | xargs grep "profit"
You need to use {} with various command which take more than two arguments at a time. For example mv command need to know the file name. The following will find all .bak files in or below the current directory and move them to ~/.old.files directory:
find . -name "*.sh" -print0 | xargs -0 -I {} mv {} ~/back.scripts
You can rename {} to something else. In the following example {} is renamed as file. This is more readable as compare to previous example:
find . -name "*.sh" -print0 | xargs -0 -I file mv file ~/back.scripts
Where,
-0 If there are blank spaces or characters (including newlines) many commands will not work. This option take cares of file names with blank space.
-I Replace occurrences of replace-str in the initial-arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character.
find
(here:-name "*.txt")
, it will execute theexec
part, I think in the same process context. On the other side, piping means to create two different processes, one reading the output of the other (to be exact: usually STDIN of the second process reads STDOUT of the first). So they run in parallel. – ridgy Jan 31 '17 at 19:54find / -name ".txt" | args cp /junk
the command on the left will fully complete and then feed the results into the command on the right. Where as with
find / -name ".txt" -exec cp {} /junk ;
will perform the copy each time a match is hit even before the find cmd is fully complete.
Is that correct?
– microscope Jan 31 '17 at 20:51for i in $(find ...); do ...
; this question is asking aboutfind ... | ...
andfind ... -exec ...
. the answers are completely different. – strugee Feb 01 '17 at 01:39xargs
is just a different method of "looping over the output." On a side note, look over the questions in this list and see how many of them are exactly asking the question, "Why does my shell script choke on whitespace or other special characters?" (Spoiler: it's very few, yet they are all correctly closed as duplicates.) – Wildcard Feb 01 '17 at 01:45for
question, since that involves whitespace and special characters as well as the fact that you're slurping the entire file list into memory all at once. though given OP's accepted answer (which I couldn't see in Review) it seems my interpretation may be incorrect. – strugee Feb 01 '17 at 01:57