find . -name "filename including space" -print0 | xargs -0 ls -aldF > log.txt find . -name "filename including space" -print0 | xargs -0 rm -rdf
Is it possible to combine these two commands into one so that only 1 find will be done instead of 2?
I know for xargs -I there may be ways to do it, which may lead to errors when proceeding filenames including spaces. Any guidance is much appreciated.
Two Types of Commands Using Multiple Arguments Commands can have multiple arguments in two scenarios: All command arguments – COMMAND ARG1 ARG2 ARG3. Option arguments – for example, COMMAND -a ARG1 -b ARG2 -c ARG3.
Running Multiple Commands as a Single Job We can start multiple commands as a single job through three steps: Combining the commands – We can use “;“, “&&“, or “||“ to concatenate our commands, depending on the requirement of conditional logic, for example: cmd1; cmd2 && cmd3 || cmd4.
The Operators &&, ||, and ; The first logical operator we will be looking at will be the AND operator: &&. In Bash, it is used to chain commands together. It can also be used to run two different scripts together.
find . -name "filename including space" -print0 | xargs -0 -I '{}' sh -c 'ls -aldF {} >> log.txt; rm -rdf {}'
Ran across this just now, and we can invoke the shell less often:
find . -name "filename including space" -print0 | xargs -0 sh -c ' for file; do ls -aldF "$file" >> log.txt rm -rdf "$file" done ' sh
The trailing "sh" becomes $0 in the shell. xargs
provides the files (returrned from find
) as command line parameters to the shell: we iterate over them with the for loop.
If you're just wanting to avoid doing the find
multiple times, you could do a tee
right after the find
, saving the find
output to a file, then executing the lines as:
find . -name "filename including space" -print0 | tee my_teed_file | xargs -0 ls -aldF > log.txt cat my_teed_file | xargs -0 rm -rdf
Another way to accomplish this same thing (if indeed it's what you're wanting to accomplish), is to store the output of the find
in a variable (supposing it's not TB of data):
founddata=`find . -name "filename including space" -print0` echo "$founddata" | xargs -0 ls -aldF > log.txt echo "$founddata" | xargs -0 rm -rdf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With